Vue之watch出现newValue and oldValue
2020-05-14 本文已影响0人
studentliubo
fd: {
handler: function (newV, old) {
// 此处打印的结果 newV与old相同
console.log('newV, old: ', newV, old)
},
deep: true
}
mounted () {
// data from server
this.fd = Object.assign(this.fd, data)
}
现象:
watch基本数据类型时正常,watch Object时就会出现这种问题。
官方解释:
image.png案例
data: {
model: {
title: null,
props: {
prop1: 1,
prop2: 2,
},
}
},
watch: {
computedModel: {
deep: true,
handler(newValue, oldValue) => {
console.log('Change: ', this.getDifference(oldValue, newValue))
}
}
},
computed: {
computedModel() {
return lodash.cloneDeep(this.model)
}
},
methods: {
getDifference() {
function changes(object, base) {
return lodash.transform(object, function(result, value, key) {
if (!lodash.isEqual(value, base[key])) {
result[key] = (lodash.isObject(value) && lodash.isObject(base[key])) ? changes(value, base[key]) : value
}
})
}
return changes(object, base)
}
},