原文地址:關於 vue 不能 watch 數組變化 和 對象變化的解決方案vue
vue 監聽數組和對象的變化數組
vue 實際上能夠監聽數組變化,好比:this
data () { return { watchArr: [], }; }, watchArr (newVal) { console.log('監聽:' + newVal); }, created () { setTimeout(() => { this.watchArr = [1, 2, 3]; }, 1000); },
再如使用 splice(0, 2, 3) 從數組下標 0 刪除兩個元素,並在下標 0 插入一個元素 3:spa
data () { return { watchArr: [1, 2, 3], }; }, watchArr (newVal) { console.log('監聽:' + newVal); }, created () { setTimeout(() => { this.watchArr.splice(0, 2, 3); }, 1000); },
push 數組也可以監聽到code
可是,數組在下面兩種狀況沒法監聽:對象
舉例沒法監聽數組變化的狀況blog
data () { return { watchArr: [{ name: 'krry', }], }; }, watchArr (newVal) { console.log('監聽:' + newVal); }, created () { setTimeout(() => { this.watchArr[0].name = 'xiaoyue'; }, 1000); },
data () { return { watchArr: [{ name: 'krry', }], }; }, watchArr (newVal) { console.log('監聽:' + newVal); }, created () { setTimeout(() => { this.watchArr.length = 5; }, 1000); },
data () { return { watchArr: [{ name: 'krry', }], }; }, watchArr (newVal) { console.log('監聽:' + newVal); }, created () { setTimeout(() => { this.$set(this.watchArr, 0, {name: 'xiaoyue'}); }, 1000); },
使用數組 splice 方法能夠監聽,例子上面有get
使用臨時變量直接賦值的方式,原理與直接賦值數組同樣console
data () { return { watchArr: [{ name: 'krry', }], }; }, watchArr (newVal) { console.log('監聽:' + newVal); }, created () { setTimeout(() => { let temp = [...this.watchArr]; temp[0] = { name: 'xiaoyue', }; this.watchArr = temp; }, 1000); },
vue 能夠監聽直接賦值的對象
this.watchObj = {name: 'popo'};
vue 不能監聽對象屬性的添加、修改、刪除
mounted () { // 這裏使用深度監聽 blog 對象的屬性變化,會觸發 getCatalog 方法 this.$watch('blog', this.getCatalog, { deep: true, }); },
this.$set(this.watchObj, 'age', 124);
delete this.watchObj[‘name’](vue 沒法監聽 delete 關鍵字來刪除對象屬性)
this.watchObj = Object.assign({}, this.watchObj, { name: 'xiaoyue', age: 15, });