MENU

Vue3中watch属性与watchEffect

July 15, 2022 • vue

监听基础类型

const nums = ref(9)

watch(nums, (newValue, oldValue) => {
    console.log('watch 已触发', newValue)
})

监听复杂类型

const demo = reactive({
    name: 'w',
    nickName: 'f',
    soulmate: {
        name: '',
        nickName: ''
    }
})

监听整个对象

watch(demo, (newValue, oldValue) => {
    console.log('watch 已触发', newValue)
})

自动开启{deep:true} , 所有子属性的更改都会触发监听事件

如果对象是使用 ref 定义的,那么监听要写为demo.value ,因为 ref 调用 reactive 生成 Proxy 对象,放在了 value 中,要动态监视,一定是监视响应式的结构,Proxy 或 RefImpl

监听某个属性

// 监听 demo 对象的 name 属性

watch(() => demo.name, (newValue, oldValue) => {
    console.log('watch 已触发', newValue)
})

注意使用箭头函数

只监听子属性

watch(() => ({ ...demo }), (newValue, oldValue) => {
    console.log('watch 已触发', newValue)
})

监听所有属性

watch(() => demo, (newValue, oldValue) => {
    console.log('watch 已触发', newValue)
}, { deep: true })

效果与第一个一样

组合监听

watch([() => demo.name, nums], ([newName, newNums], [oldName, oldNums]) => {
    console.log('watch 已触发: name', newName)
    console.log('watch 已触发: nums', newNums)
})

watchEffect

const number = reactive({ count: 0 });
const countAdd = () => {
  number.count++;
};
watchEffect(()=>{
  console.log("新的值:", number.count);
})
  • 与计算属性相似,根据所依赖的数据改变来触发监听事件
  • 计算属性注重结果,要返回值;watcheffect 注重函数体