Vue2和Vue3中的watch函数作用是一样的,用来监测数据的变化并在数据变化时触发对应的回调函数,但Vue2和Vue3中的watch在使用的细节上有所不同,Vue3中的watch在监测reactive定义的响应式数据时,oldValue(旧的值)无法正确的获取到,不同的还有deep配置(深度监视),在Vue2中想要监测到嵌套对象里的数据时需要手动开启deep配置,而Vue3中是强制开启deep配置的。
下面来举例说一下Vue3中面对不同的监测数据需求,应该如何正确的使用watch函数。
watch(sum, (newValue, oldValue) => {
consloe.log('监测到sum变化了', newValue, oldValue)
}, {immediate: true})
//Vue2中的配置项需按对象的形式配置在第三个参数中
watch([sum, msg], (newValue, oldValue) => {
console.log("监测到sum或msg值被修改了", newValue, oldValue);
});
watch(person, (newValue, oldValue) => {
console.log("person被修改了", newValue, oldValue);
});
//无法正确的获取oldValue
watch(() => {return person.age}, //第一个参数,要检测的一个数据作为箭头函数的返回值
(newValue, oldValue) => {
console.log("监测到person的age改变了", newValue, oldValue);
}
);
watch(
[
() => {
return person.name;
},
() => {
return person.age;
},
], //第一个参数,要检测的多个数据分别作为箭头函数的返回值(数组形式)
(newValue, oldValue) => {
console.log("person的age改变了", newValue, oldValue);
}
);
watch(
() => {
return person.job; //job是深层数据
},
(newValue, oldValue) => {
console.log("job被修改了", newValue, oldValue);
},
{ deep: true } //需手动开启deep配置才能监测到更深层次的数据
);