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.
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>
<v-btn color="info" @click="eliminarTarea(item.id)">Eliminar</v-btn>
And for your JS:
this.listaTareas = this.listaTareas.filter(i=>i.id != id)
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
}
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.
You can also use .$delete:
remove (index) {
this.$delete(this.finds, index)
}
sources:
Why not just omit the method all together like:
v-for="(event, index) in events"
...
<button ... @click="$delete(events, index)">