博客地址:关于 vue 不能 watch 数组变化 和 对象变化的解决方案
vue 监听数组和对象的变化
vue 实际上可以监听数组变化,比如:
data () {
return {
watchArr: [],
};
},
watchArr (newVal) {
console.log('监听:' + newVal);
},
created () {
setTimeout(() => {
this.watchArr = [1, 2, 3];
}, 1000);
},
再如使用 splice(0, 2, 3) 从数组下标 0 删除两个元素,并在下标 0 插入一个元素 3:
data () {
return {
watchArr: [1, 2, 3],
};
},
watchArr (newVal) {
console.log('监听:' + newVal);
},
created () {
setTimeout(() => {
this.watchArr.splice(0, 2, 3);
}, 1000);
},
push 数组也能够监听到
但是,数组在下面两种情况无法监听:
举例无法监听数组变化的情况
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);
},
上面的 watchArr 变成
data () {
return {
watchArr: [{
name: 'krry',
}],
};
},
watchArr (newVal) {
console.log('监听:' + newVal);
},
created () {
setTimeout(() => {
this.$set(this.watchArr, 0, {name: 'xiaoyue'});
}, 1000);
},
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,
});