1.监听变量
watch: {
totalCount(value) {
const totalPage = Math.ceil(value / this.pageSize);
if (this.pageNo > totalPage) {
this.pageNo = Math.max(1, totalPage);
}
}
},
2.监听对象 deep:true(深度监听)
watch: {
'formValues.mamsId': function(n, o) {
if (n) {
this.disabled = true;
}
},
'formValues.relativeAlbum': {
handler(n, o) {
if (n.status > 1) {
this.disabled = true;
} else if (n.status === 1) {
// 用户有切换数据类型的权限 并且切换没有提示
this.disabled = false;
}
},
deep: true
}
}
3.监听数组
data () {
return {
nameList: ['jiang', 'ru', 'yi']
}
},
methods: {
handleClick () {
// 通过push,unshift等方法改变数组可以通过watch监听到
this.nameList.push('瑶')
// 直接通过数组下标进行修改数组无法通过watch监听到
this.nameList[2] = '爱'
// 通过$set修改数组可以通过watch监听到
this.$set(this.nameList, 2, '张')
// 利用数组splice方法修改数组可以通过watch监听到
this.nameList.splice(2, 1, '蒋如意')
}
},
watch: {
nameList (newVal) {
console.log(newVal)
}
}
附录:
Watch 与 computed的区别:
Watch:watch用于观察和监听页面上的vue实例,当你需要在数据变化响应时,执行异步操作,或高性能消耗的操作,那么watch为最佳选择
computed :可以关联多个实时计算的对象,当这些对象中的其中一个改变时都会触发这个属性具有缓存能力,所以只有当数据再次改变时才会重新渲染,否则就会直接拿取缓存中的数据。