3

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?

2

2 Answers 2

6

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/[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>

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, this is cleanest and simplest way to do it!
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);
}

1 Comment

This works for Vue 2.2.0+. The doc: v2.vuejs.org/v2/api/#Vue-delete

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.