vue数组对象修改触发视图更新

直接修改数组元素是没法触发视图更新的,如数组

this.array[0] = {
    name: 'meng',
    age: 22
}

修改array的length也没法触发视图更新,如this

this.array.length = 2;

触发视图更新的方法有以下几种spa

1. Vue.setcode

能够设置对象或数组的值,经过key或数组索引,能够触发视图更新对象

数组修改blog

Vue.set(array, indexOfItem, newValue)
this.array.$set(indexOfItem, newValue)

对象修改递归

Vue.set(obj, keyOfItem, newValue)
this.obj.$set(keyOfItem, newValue)

2. Vue.delete索引

删除对象或数组中元素,经过key或数组索引,能够触发视图更新it

 

数组修改io

Vue.delete(array, indexOfItem)
this.array.$delete(indexOfItem)

对象修改

Vue.delete(obj, keyOfItem)
this.obj.$delete(keyOfItem)

3. 数组对象直接修改属性,能够触发视图更新

this.array[0].show = true;
this.array.forEach(function(item){
    item.show = true;
});

4. splice方法修改数组,能够触发视图更新

this.array.splice(indexOfItem, 1, newElement)

5. 数组赋值为新数组,能够触发视图更新

this.array = this.array.filter(...)
this.array = this.array.concat(...)

6. 用Object.assign或lodash.assign能够为对象添加响应式属性,能够触发视图更新

//Object.assign的单层的覆盖前面的属性,不会递归的合并属性
this.obj = Object.assign({},this.obj,{a:1, b:2})

//assign与Object.assign同样
this.obj = _.assign({},this.obj,{a:1, b:2})

//merge会递归的合并属性
this.obj = _.merge({},this.obj,{a:1, b:2})

7.Vue提供了以下的数组的变异方法,能够触发视图更新

push()
pop()
shift()
unshift()
splice()  
sort()
reverse()
相关文章
相关标签/搜索