一、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
- 修正数组的长度时,比方arr.length=newLength
举例没法监听数组变化的状况
1、应用索引直接修正数组值
data () {
return {
watchArr: [{
name: 'krry',
}],
};
},
watchArr (newVal) {
console.log('监听:' + newVal);
},
created () {
setTimeout(() => {
this.watchArr[0].name = 'xiaoyue';
}, 1000);
},
2、修正数组的长度
长度大于原数组就将后续元素设置为undefined
长度小于原数组就将过剩元素截掉
data () {
return {
watchArr: [{
name: 'krry',
}],
};
},
watchArr (newVal) {
console.log('监听:' + newVal);
},
created () {
setTimeout(() => {
this.watchArr.length = 5;
}, 1000);
},