vue 监听数组和对象的变化
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 数组也能够监听到
vue 无法监听数组变化的情况
但是,数组在下面两种情况无法监听:
利用索引直接设置一个数组项时,例如:arr[indexOfItem] = newValue;
修改数组的长度时,