Vue修改数组、对象并且触发视图更新的方法以及原理

发布时间 2023-06-02 15:32:00作者: 当下是吾

一、数组

 

items: ['a', 'b', 'c'];//一个普通的数组 
this.items[1] = 'x' ;//修改已有项
this.items[3] = 'd' ;//新增一项
this.item.length = 2;//修改数组的长度
//一个对象数组
msg: [{id: 1,selected: true, title: 'aaa',},
      {id: 2,selected: false, title: 'bbb'},
      {id: 3,selected: true, title: 'ccc'}]

this.msg[0] = { id : 1,selected : true, title : 'AAA'} //修改已有项
this.msg[3] = { id : 4,selected : true, title : 'DDD'} //新增一项
this.msg[0].child = "Child";//给数组的某一项新增属性

像上面这样,直接通过数组的下标去新增、修改数组的某一项、修改数组的长度,这些操作都不会被vue检测到 —— 数组的值虽然发生了变化,但是页面不会更新

解决方案:

 

方法详解

Array.splice(index,num,newItem)

  • Array 要操作的数组

  • index 要删除元素的下标

  • num 要删除元素的个数(num=0则不删除)

  • newItem 删除元素后想要在原位置替换的值(可以是0个或者多个)

this.$set(Array,index,newItem)

  • Array 要操作的数组

  • index 要修改元素的下标

  • newItem 修改之后的新值

items: ['a', 'b', 'c'];//一个普通的数组 

this.$set(items,1,'x');//修改已有项
this.items.splice(1,1,'x');//修改已有项

this.$set(items,3,'d');//新增一项
this.items.splice(3,1,'d');//新增一项

this.items.splice(2);//修改数组的长度


//一个对象数组
msg: [{id: 1,selected: true, title: 'aaa',},
      {id: 2,selected: false, title: 'bbb'},
      {id: 3,selected: true, title: 'ccc'}]
      
this.$set(msg,0,{ id : 1,selected : true, title : 'AAA' }); //修改已有项
this.msg.splice(0,1,{ id : 1,selected : true, title : 'AAA' }); //修改已有项

this.$set(msg,3,{ id : 4,selected : true, title : 'DDD' }); //新增一项
this.msg.splice(3,0,{ id : 4,selected : true, title : 'DDD' }); //新增一项

Vue提供了如下的数组的变异方法,可以触发视图更新:

注意:以下方法都会改变原数组!

 

push() - 往数组最后面添加一个元素,成功返回当前数组的长度
pop() - 删除数组的最后一个元素,成功返回删除元素的值
shift() - 删除数组的第一个元素,成功返回删除元素的值
unshift() - 往数组最前面添加一个元素,成功返回当前数组的长度
splice() - 向/从数组中添加/删除项目,然后返回被删除的项目
sort() - 使数组按照字符编码默认从小到大排序,成功返回排序后的数组
reverse() - 将数组倒序,成功返回倒序后的数组

以下常用的数组操作都不会改变现有的数组,而是返回一个新数组。

slice() 从已有数组中截取选定的元素,并返回一个由这些元素组成的新数组。
concat() 方法用于连接两个或多个数组,返回被连接数组的一个副本。
join() 方法用于把数组中的所有元素放入一个字符串,返回一个字符串。
filter() 通过检查指定数组中符合条件的所有元素,并返回一个由这些元素组成的新数组。

值得强调的是:利用索引直接修改一个数组项中已有的的属性值,数组的值会改变,页面也会更新!

 

//一个对象数组
msg: [{id: 1,selected: true, title: 'aaa',},
      {id: 2,selected: false, title: 'bbb'},
      {id: 3,selected: true, title: 'ccc'}]
      
this.msg[0].title = "AAA";

 

二、对象

 

 

 

参考文章

vue响应式原理https://cn.vuejs.org/v2/guide/reactivity.html