watch的属性值
TypeScript
复制代码
handler:回调函数, 即监听到变化时应该执行的函数,可以是单独的函数或带有 immediate 和 deep 属性的对象
watch: {
someProperty: function(newVal, oldVal) {
// 处理逻辑
}
}
deep: 其值是true或false, 当属性值是对象或数组时,深度观察会监控对象内部所有层级的变化。
watch: {
someObject: {
handler(newVal, oldVal) {
// 处理逻辑
},
deep: true
}
}
immediate: 值是true或false,首次绑定时立即执行回调函数
watch: {
someProperty: {
handler(newVal, oldVal) {
// 处理逻辑
},
immediate: true
}
}
vue2写法:
TypeScript
复制代码
//基本用法
watch:{
avatar(navl,oval){
console.log(navl,'navl');
console.log(oval,'oval');
}
},
//深度监听
watch: {
user: {
handler(nval,oval) {
console.log(nval,oval);
},
deep: true,
}
},
//立即执行
watch: {
user: {
handler(nval,oval) {
console.log(nval,oval);
},
immediate: true
}
},
//观察数组中特定项的变化
watch: {
'user[0]': function(newVal, oldVal) {
console.log('user[0] changed from', oldVal, 'to', newVal);
}
//监听多个数据源
watch: {
property1(newVal, oldVal) {
console.log('property1 changed from', oldVal, 'to', newVal);
},
property2(newVal, oldVal) {
console.log('property2 changed from', oldVal, 'to', newVal);
}
}
vue3写法:
TypeScript
复制代码
import { watch } from 'vue';
//基本用法
watch(avatar, (newVal, oldVal) => {
console.log('avatarchanged from', oldVal, 'to', newVal);
});
//深度管察
watch(
() => user,
(nval,oval) => {
console.log(val, oval)
},
{ deep:true },
)
//立即执行
watch(
() => user,
(nval,oval) => {
console.log(val, oval)
},
{ immediate: true },
)
//使用回调函数对象
watch(
someProperty,
{
handler(newVal, oldVal) {
console.log('someProperty changed from', oldVal, 'to', newVal);
},
immediate: true,
deep: true
}
);