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

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

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

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

this.array.length = 2;

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

1. Vue.set

可以设置对象或数组的值,通过key或数组索引,可以触发视图更新

数组修改

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

对象修改

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

2. Vue.delete

删除对象或数组中元素,通过key或数组索引,可以触发视图更新

 

数组修改

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()

 

posted @   全玉  阅读(43184)  评论(1编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
历史上的今天:
2017-02-28 点击其他区域关闭dialog
点击右上角即可分享
微信分享提示