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

You're using splice in a wrong way.

The overloads are:

array.splice(start)

array.splice(start, deleteCount)

array.splice(start, deleteCount, itemForInsertAfterDeletion1, itemForInsertAfterDeletion2, ...)

Start means the index that you want to start, not the element you want to remove. And you should pass the second parameter deleteCount as 1, which means: "I want to delete 1 element starting at the index {start}".

So you better go with:

deleteEvent: function(event) {
  this.events.splice(this.events.indexOf(event), 1);
}

Also, you're using a parameter, so you access it directly, not with this.event.

But in this way you will look up unnecessary for the indexOf in every delete, for solving this you can define the index variable at your v-for, and then pass it instead of the event object.

That is:

v-for="(event, index) in events"
...

<button ... @click="deleteEvent(index)"

And:

deleteEvent: function(index) {
  this.events.splice(index, 1);
}

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

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
}

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/[email protected]/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>