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

前端 未结 8 1098
小蘑菇
小蘑菇 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"
    ...
    
    

    And:

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

提交回复
热议问题