104

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.

HTML

    <div class="list-group">

        <div class="list-group-item" v-for="event in events">
            <h4 class="list-group-item-heading">
                {{ event.name }}
            </h4>

            <h5>
                {{ event.date }}
            </h5>

            <p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>

            <button class="btn btn-xs btn-danger" @click="deleteEvent(event)">Delete</button>
        </div>

    </div>
</div>

JS(Vue)

new Vue ({
    el: '#app',

    data: {
        events: [
            {
                id: 1,
                name: 'Event 1',
                description: 'Just some lorem ipsum',
                date: '2015-09-10'
            },
            {
                id: 2,
                name: 'Event 2',
                description: 'Just another lorem ipsum',
                date: '2015-10-02'
            }
        ],

        event: { name: '', description: '', date: '' }
    },

    ready: function() {

    },

    methods: {

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

        // Adds an event to the existing events array
        addEvent: function() {
            if(this.event.name) {
                this.events.push(this.event);
                this.event = { name: '', description: '', date: '' };
            }
        }

    } // end of methods

});

I've tried to pass the event to the function and than delete that one with the slice function, I thought it was that code for deleting some data from the array. What is the best en cleanest way to delete data from the array with a simpleb button and onclick event?

bbholzbb
  • 1,602
  • 3
  • 17
  • 28
Giesburts
  • 5,096
  • 10
  • 34
  • 70
  • Does this answer your question? [How to remove specific item from array?](https://stackoverflow.com/questions/5767325/how-to-remove-specific-item-from-array) – ponury-kostek Feb 28 '20 at 18:37

8 Answers8

170

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);
}
Community
  • 1
  • 1
Edmundo Rodrigues
  • 6,057
  • 3
  • 23
  • 33
  • Awesome, I already thought that I was using splice wrong. Can you tell me what the difference is between splice and slice? Thanks! – Giesburts Mar 27 '17 at 12:40
  • 1
    Sure. Basically, sPlice modifies the original array, while slice creates a new array. More info here: http://www.tothenew.com/blog/javascript-splice-vs-slice/ – Edmundo Rodrigues Mar 27 '17 at 12:54
  • You can use $remove as a shorthand also. – Chris Dixon May 09 '18 at 11:13
  • 3
    @EdmundoRodrigues, thanks for this one '_you can define the index variable at your `v-for`_' :) I love SO because of such gems. – Valentine Shi Feb 16 '19 at 08:28
  • @ Edmundo Rodrigues Thanks. It was really nice. I was just deleting with the index instead the index of object. thanks a lot – priya_21 Apr 16 '19 at 14:05
  • i think this is not a right answer for vue.js. you can use $delete method.Only in 2.2.0+: Also works with Array + index. – syam lal Jul 06 '19 at 06:01
84

You can also use .$delete:

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

sources:

Katinka Hesselink
  • 2,446
  • 16
  • 23
35

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
}
Afraz Ahmad
  • 4,066
  • 23
  • 32
6

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>
Yevgeniy Afanasyev
  • 27,544
  • 16
  • 134
  • 147
  • this is helpful, but can you help me on this? I got stuck when using component.. https://codepen.io/wall-e/pen/dQrmpE?editors=1010 – w411 3 Dec 03 '18 at 10:46
4

You can delete item through id

<button @click="deleteEvent(event.id)">Delete</button>

Inside your JS code

deleteEvent(id){
  this.events = this.events.filter((e)=>e.id !== id )
}

Vue wraps an observed array’s mutation methods so they will also trigger view updates. Click here for more details.

You might think this will cause Vue to throw away the existing DOM and re-render the entire list - luckily, that is not the case.

Masum Billah
  • 1,435
  • 16
  • 20
1
<v-btn color="info" @click="eliminarTarea(item.id)">Eliminar</v-btn>

And for your JS:

this.listaTareas = this.listaTareas.filter(i=>i.id != id)
Cà phê đen
  • 1,815
  • 2
  • 17
  • 18
  • 1
    Your answer is almost the same as others and not better than others. So it's not worthy to post this. – foxiris Jun 19 '19 at 03:35
1

Why not just omit the method all together like:

v-for="(event, index) in events"
...
<button ... @click="$delete(events, index)">
James Jones
  • 8,061
  • 5
  • 32
  • 44
0

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.

Kaushik shrimali
  • 729
  • 6
  • 13