在这篇文章中,我们将逐步指导如何在Vuejs中从一个数组中删除一个元素。

在vuejs或javascript中,有多种方法可以从数组中删除一个项目

如果你要从数组中删除一个元素,原来的数组不会发生变化,它只是返回新创建的数组。

接合方法从数组中删除对象

splice 是数组中的一个内置方法,用于从数组中删除一个元素,并返回带有删除列表的新数组。

splice(startindex)
splice(startindex, countofelements)

startindex是一个起始索引,在这个索引上的元素被删除 countofelements是要从startindex中删除的元素数量。

所以,你可以使用index 和Countofelements来删除拼接object

让我们在data 函数的vuejs 中声明一个数组。

 employees: [
            { name: 'John', id: 1 },
            { name: 'Eric', id: 3 },
            { name: 'Rob', id: 4 },
            { name: 'Andrew', id: 8 }

在下面的例子中,使用index从数组中删除一个对象

在模板中,使用v-for 指令和index语法来显示对象的列表。

要从一个数组中删除一个对象,将index方法传递给@click event hander

Delete By Object
  this.employees.splice(index, 1); remove an starting index position element 
    removeEmployeeByIndex: function(index){
      this.employees.splice(index, 1);

使用数组过滤器方法直接从数组中删除一个对象

这是另一种删除元素的方法。这不会改变原来的数组,但是它将通过删除一个数组对象返回新的列表。

filter in array 过滤要删除的元素并返回没有元素的新数组。

    removeEmployeeByObject: function(emp){
      const filtersList = this.employees.filter(element => element !== emp)
      this.employees=filtersList

vue删除方法

对于Vue 2.2.0+版本,使用vue.delete

下面是一个语法

Vue.delete( object/array, name/index )

第一个参数是一个对象的迭代或数组 第二个参数是一个对象的索引或属性名称

在javascript代码中,创建一个方法来删除一个对象

使用delete 方法,你可以从一个对象或数组中删除一个属性。

如果你从对象中删除一个属性,它就会反应性地触发视图的更新。

deleteEmpl: function(index){
    this.$delete(this.employees, index)
by delete an object from array, It triggers view updates reactively.
## Conclusion,
On this tutorial, you learned multiple ways to remove an object from an array in vuejs applicaiton
- Splice method with index approach
- remove by value using Array filter 
- vue delete 
        Android 工程师 @ 阿里巴巴
        1232.7k
      
粉丝