在VUE中改变数组、对象。页面没有变化

5,503 阅读1分钟

有的时候,我们在vue中动态添加了一些属性,发现页面并没有响应这些变化。可能是我们添加的方法不对

官网上面有提醒过,由于 javascript 的限制,vue 不能检测到以下变动的数组

1、直接利用索引设置一个值: this.dataList[indexOfItem] = newValue;

2、修改数组长度: this.dataList.length = 5;

第一个问题,有两种方法都可以实现相同的效果,并且触发状态更新

// Vue.set
Vue.set(this.dataList, indexOfItem, newValue);

// Array.prototype.splice
this.dataList.splice(indexOfItem, 1, newValue);

第二个问题可以使用 splice

this.dataList.splice(newLength);

对象更改检测注意


还是由于javascript的限制,vue不能检测到对象属性的添加和删除

可以使用 Vue.set(object, key, value) 向嵌套对象添加响应式属性。

    var vm = new Vue({
        el: '#app',
        data: {
            userData: {
                name: '小明'
            }
        }
    })

可以添加一个 age 属性到userData 中。

Vue.set(vm.userData, 'age', 27);
在组件中这样写
this.$set(this.userData, 'age', 27);

有时候可能会添加多个属性,这样的话,最好是创建一个新的对象

vm.userData = Object.assign({}, vm.userData, {
    age: 27,
    branch: 'aaa'
})

this.user = Object.assign({}, this.userData, {
    age: 27,
    branch: 'aaa'
})