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

前端 未结 8 1064
小蘑菇
小蘑菇 2020-11-29 02:24

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.

相关标签:
8条回答
  • 2020-11-29 03:00

    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);
    }
    
    0 讨论(0)
  • 2020-11-29 03:00

    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.

    0 讨论(0)
提交回复
热议问题