1、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数组也可以监听到
2、vue没法监听数组变化的状况
可是数组在下面两种状况下没法监听this
举例没法监听数组变化的状况
一、利用索引直接修改数组值code
data () { return { watchArr: [{ name: 'krry', }], }; }, watchArr (newVal) { console.log('监听:' + newVal); }, created () { setTimeout(() => { this.watchArr[0].name = 'xiaoyue'; }, 1000); },
二、修改数组的长度
长度大于原数组就将后续元素设置为undefined
长度小于原数组就将多余元素截掉索引
data () { return { watchArr: [{ name: 'krry', }], }; }, watchArr (newVal) { console.log('监听:' + newVal); }, created () { setTimeout(() => { this.watchArr.length = 5; }, 1000); },