1.监听一个具体的数据属性:
watch: {
count(newValue, oldValue) {
// 当count属性发生变化时执行的回调函数
console.log('count 变化了', newValue, oldValue);
}
}
2.监听一个计算属性:
watch: {
fullName(newValue, oldValue) {
// 当fullName计算属性的值发生变化时执行的回调函数
console.log('fullName 变化了', newValue, oldValue);
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName;
}
}
3.监听一个对象内部的属性:
watch: {
'user.name': {
handler(newValue, oldValue) {
// 当user对象的name属性发生变化时执行的回调函数
console.log('user.name 变化了', newValue, oldValue);
},
deep: true
}
},
data() {
return {
user: {
name: 'John'
}
};
}
4.使用immediate选项立即执行监听回调函数:
watch: {
count: {
handler(newValue, oldValue) {
// 当count属性发生变化时执行的回调函数
console.log('count 变化了', newValue, oldValue);
},
immediate: true
}
}
5.动态地创建一个侦听器
this.$watch(source, callback(newValue, oldValue), options)
// 5.1:我们使用了$watch()方法来监听count属性的变化。第一个函数返回我们想要观察的表达式,第二个函数是回调函数,在表达式的值发生变化时被调用。
this.$watch(
function() {
return this.count;
},
function(newValue, oldValue) {
console.log('count 变化了', newValue, oldValue);
}
);
// 5.2:传入一个字符串作为观察的数据或表达式,类似于组件的watch选项
this.$watch('count', function(newValue, oldValue) {
console.log('count 变化了', newValue, oldValue);
});