vue之watch监听总结(记笔记类别)
写法1:这种写法比较简单,注意,这种方法只能监听一些简单数据类型
watch: {
//isDragging是需要监听的数据
isDragging(newV,oldV) {
if (newV) {
this.delayedDragging = true;
}
this.$nextTick(() => {
this.functionTest()
});
}
}
写法2:这种写法和上面的写法类似,同样是不能监听对象,但可以对对象中的否个属性单独拿出来进行监听
watch: {
//监听对象myData的regionCode属性的数据变化
"myData.regionCode":function(newVal,oldVal){
this.functionTest()
}
},
写法3:这种写法比较全面,设置deep:true
可对对象进行监听
watch: {
myData: {
handler(newVal, oldVal) {
console.log('newVal', newVal);
console.log('oldVal', oldVal);
},
//immediate为true时则立即触发回调函数;如果为false,则和上面的例子一样,不会立即执行回调。
immediate: true,
//深层监听,设置为true可对对象进行监听
deep:true
}
}
注意:有时候写在watch中的方法无法执行,这时需要像写法1中的一样,加一个
this.$nextTick(()=>{})
就可以了!