项目场景:
需要监听多个字段的变化时,一个一个去监听很麻烦,所以把他们搞成一个对象的属性,然后去监听这个对象。
问题描述
然而我在监听中去输出newVal,和oldVal时,发现值相同
watch: {
priceForm: {
handler: function (newVal, oldVal) {
console.log('newVal', newVal, 'oldVal', oldVal)
this.getPrice()
},
deep: true
}
}
原因分析:
Vue官方的解释是:在变更(不是替换)对象或数组时,新值与旧值相同,因为他们指向同一数组或对象,Vue不会保留变更前值的副本。
解决方案:
所以我们这里利用计算属性来使其保留
watch: {
priceFormData: {
handler: function (newVal, oldVal) {
console.log('newVal', newVal)
console.log('oldVal', oldVal)
this.getPrice()
},
deep: true
}
},
computed: {
priceFormData () {
return JSON.parse(JSON.stringify(this.priceForm))
}
}
问题描述:
这样修改以后oldVal与newVal值相同的问题已经可以了,然而因为我初始化的时候会给对象中的所有属性都赋值,这样就会执行很多次,但是我的初衷其实是初始化时只执行一次,其它时候发生改变时再去监听
解决方案
利用timeout延迟执行去实现初始化
watch: {
priceFormData: {
handler: function (newVal, oldVal) {
if (this.timer) {
clearTimeout(this.timer)
}
this.timer = setTimeout(() => {
this.getPrice()
}, 1000)
},
deep: true
}
},
computed: {
priceFormData () {
return JSON.parse(JSON.stringify(this.priceForm))
}
}