- vue深度監(jiān)聽表單時候,新老對象的值是相同的。
watch: {
form: {
handle (val, old) {
console.log(val) //=> {'sex':'1','userid':'1'}
console.log(old) //=> {'sex':'1','userid':'1'}
},
deep: true
}
},
其原因是vue在變異(非替換)數組或對象時,新舊值都指向同一個數組或者對象,vue不會保留變異之前的副本 vue-實例方法-數據
簡單來說:因為數據同源。雖然可以監(jiān)聽到他的變化,但是要比較數據差異就不行了。
- 如何解決watch 值相同
computed: {
ChangeForm () {
return JSON.parse(JSON.stringify(this.form))
//監(jiān)聽對象返回深拷貝form 指向新的內存地址
// 如果是數組可以 return [...new Set(selectedArry)]
}
},
watch: {
ChangeForm: {
handle (val, old) {
console.log(val) //=> {'sex':'1','userid':'1'}
console.log(old) //=> {'sex':'2','userid':'2'}
},
deep: true
}
}