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?
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?
Share Improve this question asked May 2, 2018 at 18:03 gileneuszgileneusz 1,4959 gold badges36 silver badges55 bronze badges 2- 1 Check this stackoverflow./questions/43046332/… – Zain Farooq Commented May 2, 2018 at 18:07
- @ZainFarooq thanks for this link, it seems very similar – gileneusz Commented May 2, 2018 at 18:10
2 Answers
Reset to default 6Uses 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./[email protected]/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>
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);
}