Vue 数组操作方法

操作方法

以下实例中 this.users 为数组例子

$set 方法

设置数组值

// 根据索引设置元素 方法1
this.users.$set(index, val);

// 改变数组的指定项 方法2
this.$set(arr, indexOfItem, newValue)

// 改变数组的指定项 方法3
Vue.set(数组, 索引, 新元素)  // 注意 Vue 的首字母大写

concat 方法

合并数组:

this.users = this.users.concat(anotherArr);

清空数组:

this.users = [];

push() 方法

用于向数组末尾添加元素,可添加一个或多个,返回值为数组 length

this.users.push({
    user_id: 1,
    user_name:'张三',
 })

pop() 方法

用于删除数组末尾元素,返回值为删除的元素

shift() 方法

用于删除数组第一个元素,返回值为删除的元素

unshift() 方法

用于像数组首部添加元素,可添加一个或多个,返回值为数组 length

splice() 方法

用于删除、添加、替换元素,

  • arrayObject.splice(index,howmany,item1,.....,itemX) 第一个参数 index 为元素下标,第二个参数 howmany 为删除个数,第三个及之后参数为向数组添加的元素

  • 如果只传第一个元素,则删除下标 index 后的所有元素

  • 如果传两个参数,则删除起始下标 index 开始之后的 howmany 个元素

  • 如果传三个参数,则删除起始下标 index 开始之后的 howmany 个元素,并添加 items 元素

// 在最后一个元素之前添加一个元素
this.users.splice(-1, 0, {
  user_id: 0,
  user_name:'',
});

// 删除 index 坐标元素
that.users.splice(index, 1);

// 替换下标为index的元素
this.users.splice(index, 1, val);

sort() 方法

用于对数组排序,不传参数则按照字符编码排序,也可传入一个有两个形参的回调函数,然后根据返回值排序,(此处将回调函数的参数命名为 a 和 b)

  • 若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。
  • 若 a 等于 b,则返回 0。
  • 若 a 大于 b,则返回一个大于 0 的值。
this.users.sort(function (a, b) {
    return b.user_id - a.user_id    // 3、为了效果,我写的 b.user_id - a.user_id,你也可以调换顺序试试
})

reverse() 方法

用于颠倒数组中元素的顺序

this.users.reverse()

filter 方法

过滤数组中的元素。

现在 Vue 实例中有这么一个数组:

<div id="app">
    {{ matchOO }}    // 4、在页面中渲染
</div>

var app = new Vue({
  el: '#app',
  data: {
    studyArr: ['book', 'pen', 'pencil']    // 1、一个装满了文具的数组
  },
  computed: {
    matchOO() {    // 2、计算属性中有一个 matchOO 方法,返回数组中含有 'oo' 字符串的元素
      return this.studyArr.filter(function (value) {    // 3、value 代表数组中的每一项
        return value.match(/oo/)
      }) 
    }
  }
})

因为数组中的元素,只有 "book" 才含有 "oo" ,所以返回 "book"。

注意

数组的两个变动 Vue 检测不到:

即以下操作均无法触发视图更新

// 改变数组的指定项
this.users[index] = val;

// 改变数组的长度
this.users.length = 2;