原文地址:关于 vue 不能 watch 数组变化 和 对象变化的解决方案vue
vue 监听数组和对象的变化数组
vue 实际上能够监听数组变化,好比:this
data () { return { watchArr: [], }; }, watchArr (newVal) { console.log('监听:' + newVal); }, created () { setTimeout(() => { this.watchArr = [1, 2, 3]; }, 1000); },
再如使用 splice(0, 2, 3) 从数组下标 0 删除两个元素,并在下标 0 插入一个元素 3:spa
data () { return { watchArr: [1, 2, 3], }; }, watchArr (newVal) { console.log('监听:' + newVal); }, created () { setTimeout(() => { this.watchArr.splice(0, 2, 3); }, 1000); },
push 数组也可以监听到code
可是,数组在下面两种状况没法监听:对象
举例没法监听数组变化的状况blog
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); },
data () { return { watchArr: [{ name: 'krry', }], }; }, watchArr (newVal) { console.log('监听:' + newVal); }, created () { setTimeout(() => { this.$set(this.watchArr, 0, {name: 'xiaoyue'}); }, 1000); },
使用数组 splice 方法能够监听,例子上面有get
使用临时变量直接赋值的方式,原理与直接赋值数组同样console
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, });