2

I've got basic v-for which is looping on array:

<template v-for="(item, index) in array">
    {{item.text}}
    <btn @click="delete">Delete me!</btn>
</temaplate>

I want to be able to delete an item inside my loop. How can I do it? Can I simply use splice() or delete not having index of the element I want to delete?

gileneusz
  • 1,435
  • 8
  • 30
  • 51

2 Answers2

5

Uses Array.splice().

app = new Vue({
  el: "#app",
  data: {
    items: [{'text':'a'},{'text':'b'}]
  },
  methods: {
    deleteItem: function (item, index) {
      if(this.items[index] === item) { 
      // The template passes index as the second parameter to avoid indexOf, 
      // it will be better for the performance especially for one large array
      // (because indexOf actually loop the array to do the match)
        this.items.splice(index, 1)
      } else {
        let found = this.items.indexOf(item)
        this.items.splice(found, 1)
      }
    }
  }
})
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <template v-for="(item, index) in items">
      {{item.text}}
      <button @click="deleteItem(item, index)">Delete me!</button>
  </template>
</div>
Sphinx
  • 10,519
  • 2
  • 27
  • 45
1

Just in case there are still some people who uses splice, Vue has $delete already.

In your template:

<template v-for="(item, index) in array" :key="item">
{{item.text}}
<btn @click="delete(index)">Delete me!</btn>

In your methods:

delete(index){
   this.$delete(this.array, index);
}