How to remove an item from an array in Vue.js

前端 未结 8 1063
小蘑菇
小蘑菇 2020-11-29 02:24

I am new to vue.js (2) and I am currently working on a simple event app. I\'ve managed to add events but now I would like to delete events based on clicking on a button.

相关标签:
8条回答
  • 2020-11-29 02:38

    It is even funnier when you are doing it with inputs, because they should be bound. If you are interested in how to do it in Vue2 with options to insert and delete, please see an example:

    please have a look an js fiddle

    new Vue({
      el: '#app',
      data: {
        finds: [] 
      },
      methods: {
        addFind: function () {
          this.finds.push({ value: 'def' });
        },
        deleteFind: function (index) {
          console.log(index);
          console.log(this.finds);
          this.finds.splice(index, 1);
        }
      }
    });
    <script src="https://unpkg.com/vue@2.5.3/dist/vue.js"></script>
    <div id="app">
      <h1>Finds</h1>
      <div v-for="(find, index) in finds">
        <input v-model="find.value">
        <button @click="deleteFind(index)">
          delete
        </button>
      </div>
      
      <button @click="addFind">
        New Find
      </button>
      
      <pre>{{ $data }}</pre>
    </div>

    0 讨论(0)
  • 2020-11-29 02:38
    <v-btn color="info" @click="eliminarTarea(item.id)">Eliminar</v-btn>
    

    And for your JS:

    this.listaTareas = this.listaTareas.filter(i=>i.id != id)
    
    0 讨论(0)
  • 2020-11-29 02:41

    Don't forget to bind key attribute otherwise always last item will be deleted

    Correct way to delete selected item from array:

    Template

    <div v-for="(item, index) in items" :key="item.id">
      <input v-model="item.value">
       <button @click="deleteItem(index)">
      delete
    </button>
    

    script

    deleteItem(index) {
      this.items.splice(index, 1); \\OR   this.$delete(this.items,index)
     \\both will do the same
    }
    
    0 讨论(0)
  • 2020-11-29 02:43

    Splice is the best to remove element from specific index. The given example is tested on console.

    card = [1, 2, 3, 4];
    card.splice(1,1);  // [2]
    card   // (3) [1, 3, 4]
    splice(startingIndex, totalNumberOfElements)
    

    startingIndex start from 0.

    0 讨论(0)
  • 2020-11-29 02:58

    You can also use .$delete:

    remove (index) {
     this.$delete(this.finds, index)
    }
    

    sources:

    • https://vuejs.org/v2/api/#Vue-delete
    • https://medium.com/vuejs-tips/tip-3-deleting-array-index-in-vue-js-8cc31d7214bf
    0 讨论(0)
  • 2020-11-29 02:58

    Why not just omit the method all together like:

    v-for="(event, index) in events"
    ...
    <button ... @click="$delete(events, index)">
    
    0 讨论(0)
提交回复
热议问题