博客地址:關(guān)于 vue 不能 watch 數(shù)組變化 和 對象變化的解決方案
vue 監(jiān)聽數(shù)組和對象的變化
vue 監(jiān)聽數(shù)組
vue 實際上可以監(jiān)聽數(shù)組變化,比如:
data () {
return {
watchArr: [],
};
},
watchArr (newVal) {
console.log('監(jiān)聽:' + newVal);
},
created () {
setTimeout(() => {
this.watchArr = [1, 2, 3];
}, 1000);
},
再如使用 splice(0, 2, 3) 從數(shù)組下標 0 刪除兩個元素,并在下標 0 插入一個元素 3:
data () {
return {
watchArr: [1, 2, 3],
};
},
watchArr (newVal) {
console.log('監(jiān)聽:' + newVal);
},
created () {
setTimeout(() => {
this.watchArr.splice(0, 2, 3);
}, 1000);
},
push 數(shù)組也能夠監(jiān)聽到
vue 無法監(jiān)聽數(shù)組變化的情況
但是,數(shù)組在下面兩種情況無法監(jiān)聽:
- 利用索引直接設置一個數(shù)組項時,例如:arr[indexOfItem] = newValue;
- 修改數(shù)組的長度時,例如:arr.length = newLength;
舉例無法監(jiān)聽數(shù)組變化的情況
- 利用索引直接修改數(shù)組值
data () {
return {
watchArr: [{
name: 'krry',
}],
};
},
watchArr (newVal) {
console.log('監(jiān)聽:' + newVal);
},
created () {
setTimeout(() => {
this.watchArr[0].name = 'xiaoyue';
}, 1000);
},
- 修改數(shù)組的長度
長度大于原數(shù)組就將后續(xù)元素設置為 undefined
長度小于原數(shù)組就將多余元素截掉
data () {
return {
watchArr: [{
name: 'krry',
}],
};
},
watchArr (newVal) {
console.log('監(jiān)聽:' + newVal);
},
created () {
setTimeout(() => {
this.watchArr.length = 5;
}, 1000);
},
上面的 watchArr 變成
[圖片上傳失敗...(image-f5ff59-1538822570758)]
vue 無法監(jiān)聽數(shù)組變化的解決方案
- this.$set(arr, index, newVal);
data () {
return {
watchArr: [{
name: 'krry',
}],
};
},
watchArr (newVal) {
console.log('監(jiān)聽:' + newVal);
},
created () {
setTimeout(() => {
this.$set(this.watchArr, 0, {name: 'xiaoyue'});
}, 1000);
},
使用數(shù)組 splice 方法可以監(jiān)聽,例子上面有
使用臨時變量直接賦值的方式,原理與直接賦值數(shù)組一樣
data () {
return {
watchArr: [{
name: 'krry',
}],
};
},
watchArr (newVal) {
console.log('監(jiān)聽:' + newVal);
},
created () {
setTimeout(() => {
let temp = [...this.watchArr];
temp[0] = {
name: 'xiaoyue',
};
this.watchArr = temp;
}, 1000);
},
vue 監(jiān)聽對象
vue 可以監(jiān)聽直接賦值的對象
this.watchObj = {name: 'popo'};
vue 不能監(jiān)聽對象屬性的添加、修改、刪除
vue 監(jiān)聽對象的解決方法
- 使用 this.$set(object, key, value)
- 使用深度監(jiān)聽 deep: true,只能監(jiān)聽原有屬性的變化,不能監(jiān)聽增加的屬性
mounted () {
// 這里使用深度監(jiān)聽 blog 對象的屬性變化,會觸發(fā) getCatalog 方法
this.$watch('blog', this.getCatalog, {
deep: true,
});
},
- 使用 this.
set 修改原有屬性)
this.$set(this.watchObj, 'age', 124);
delete this.watchObj['name'](vue 無法監(jiān)聽 delete 關(guān)鍵字來刪除對象屬性)
- 使用 Object.assign 方法,直接賦值的原理監(jiān)聽(最推薦的方法)
this.watchObj = Object.assign({}, this.watchObj, {
name: 'xiaoyue',
age: 15,
});