VUEJS remove Element From Lists?

2020-05-15 13:14发布

问题:

it is possible to remove specific element from lists. i tried this functions for remove element

pop() = remove last element

$remove(index) = not remove any element from lists

remove( index ) = undefined function

unshift( index ) = add new and empty element

splice( index ) = remove all element from index

please help me to remove specific element from lists.

below is my js code

var example2 = new Vue({
  el: '#example-2',
  data: {
    items: [
      { message: 'Foo' },
      { message: 'Bar' },
      { message: 'Bar1' },
      { message: 'Bar2' },
      { message: 'Bar3' },
      { message: 'Bar4' }
    ]
  },
  methods : {
    removeElement : function(index){
        this.items.$remove(index);
    }
  }
})

below is my HTML code

<ul id="example-1">
  <li v-for="(key, item) in items">
    {{ item.message }}
    <button v-on:click="removeElement(key)">remove</button>
  </li>
</ul>

回答1:

$remove is deprecated in Vue.js 2.0 and replaced by splice as stated in the docs. Make sure you add the 2nd parameter of splice for it to work.

Migration From Vue 1.x - 2.0

methods: {
  removeElement: function (index) {
    this.items.splice(index, 1);
  }
}


回答2:

You can use Vue.delete if your Vue version is 2.2.0+

Vue.delete(this.items, index);


回答3:

The $.remove feature has been replaced with $.delete.

You can call it like so:

this.$delete(this.someItems, itemIndex).

It works on Object as well as Array. With objects, you need to use a keyed object. With arrays, you pass in the index of the item you want to delete.

Here is a fiddle example: https://jsfiddle.net/james2doyle/386w72nn/

EDIT

I added an example for an array as well



回答4:

$delete can use inline in @click:

<ul id="example">
   <li v-for="(item, key) in items">
       {{ item.message }}
       <button @click="$delete(items, key)">remove</button>
   </li>
</ul>

https://vuejs.org/v2/api/#vm-delete



回答5:

Firstly, you should fix the methods key.

Then, you should pass the item to the $remove method, not the index. [ref]

https://jsfiddle.net/790og9w6/



标签: vue.js