最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - vuejs - how can I delete array item within v-for item. element? - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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./[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);
}
发布评论

评论列表(0)

  1. 暂无评论