VUE3-watch侦听
计算属性与侦听属性的区别
- computed 计算属性: 需要声明一个新的属性,得到新的数据。
- watch 侦听属性/监视属性:一直在监视某个data数据的变化,则watch中的handler函数会被调用。
写法
vue3
<template>
<div>{{counter}}</div>
<button @click="counter++">计算器++</button>
<div>{{counter2}}</div>
<button @click="counter2++">计算器2++</button>
</template>
<script>
import {
ref,
watch
} from 'vue'
export default {
setup() {
// data
let counter = ref(1)
let counter2 = ref(100)
// watch
// 被监视的数据需要具有响应式
// watch(counter, (newValue, oldValue) => {
// console.log('计算器', newValue, oldValue);
// }, {immediate: true, deep: true})
// watch(counter2, (newValue, oldValue) => {
// console.log('计算器2', newValue, oldValue);
// }, {immediate: true})
// 采用数组的方式,一次监视多个属性
watch([counter, counter2], (newValue, oldValue) => {
console.log(newValue, oldValue); // newValue和oldValue都是数组
})
// 返回一个对象
return {
counter,
counter2
}
}
}
</script>
vue2
<template>
<div>{{counter}}</div>
<button @click="counter++">计数加</button>
</template>
<script>
export default {
// vue2写法
data() {
return {
counter: 1
}
},
watch: {
// 简写形式
// 监视的是counter属性
// 注意:被监视的属性必须具有响应式的,才能监视。
// counter(newValue, oldValue){
// console.log(newValue, oldValue);
// }
// 完整写法
counter: {
immediate: true, // 开始的时候,立即执行一次handler
deep: true, // 启用深度监视
handler(newValue, oldValue) {
console.log(newValue, oldValue);
}
}
}
}
</script>
涉及内容
VUE3、ref、watch侦听
文章讲述了Vue3中计算属性和watch侦听属性的概念与区别。计算属性用于创建新属性并基于其他数据自动更新,而watch则持续监控特定数据变化并在变化时执行回调。在Vue3的例子中,展示了如何使用ref和watch监听多个属性的变化。同时,提到了在Vue2中watch的写法,包括简写和完整形式。
3850

被折叠的 条评论
为什么被折叠?



