Javascript 如何从 Vue.js 中的数组中删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43046332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:38:16  来源:igfitidea点击:

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

javascriptvuejs2

提问by Giesburts

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.

我是 vue.js (2) 的新手,目前正在开发一个简单的事件应用程序。我已经设法添加事件,但现在我想根据单击按钮删除事件。

HTML

HTML

    <div class="list-group">

        <div class="list-group-item" v-for="event in events">
            <h4 class="list-group-item-heading">
                {{ event.name }}
            </h4>

            <h5>
                {{ event.date }}
            </h5>

            <p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>

            <button class="btn btn-xs btn-danger" @click="deleteEvent(event)">Delete</button>
        </div>

    </div>
</div>

JS(Vue)

JS(Vue)

new Vue ({
    el: '#app',

    data: {
        events: [
            {
                id: 1,
                name: 'Event 1',
                description: 'Just some lorem ipsum',
                date: '2015-09-10'
            },
            {
                id: 2,
                name: 'Event 2',
                description: 'Just another lorem ipsum',
                date: '2015-10-02'
            }
        ],

        event: { name: '', description: '', date: '' }
    },

    ready: function() {

    },

    methods: {

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

        // Adds an event to the existing events array
        addEvent: function() {
            if(this.event.name) {
                this.events.push(this.event);
                this.event = { name: '', description: '', date: '' };
            }
        }

    } // end of methods

});

I've tried to pass the event to the function and than delete that one with the slice function, I thought it was that code for deleting some data from the array. What is the best en cleanest way to delete data from the array with a simpleb button and onclick event?

我试图将事件传递给函数,而不是用 slice 函数删除那个事件,我认为这是从数组中删除一些数据的代码。使用 simpleb 按钮和 onclick 事件从数组中删除数据的最好的最干净的方法是什么?

回答by Edmundo Rodrigues

You're using splicein a wrong way.

你用splice错了方法。

The overloads are:

重载是:

array.splice(start)

array.splice(start, deleteCount)

array.splice(start, deleteCount, itemForInsertAfterDeletion1, itemForInsertAfterDeletion2, ...)

array.splice(开始)

array.splice(开始,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 deleteCountas 1, which means: "I want to delete 1 element starting at the index {start}".

Start 表示您要开始的索引,而不是您要删除的元素。并且您应该将第二个参数传递deleteCount为 1,这意味着:“我想删除从索引 {start} 开始的 1 个元素”。

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.

此外,您使用的是参数,因此您可以直接访问它,而不是使用this.event.

But in this way you will look up unnecessary for the indexOfin every delete, for solving this you can define the indexvariable at your v-for, and then pass it instead of the event object.

但是通过这种方式,您将indexOf在每次删除时查找不必要的,为了解决这个问题,您可以index在您的 中定义变量v-for,然后传递它而不是事件对象。

That is:

那是:

v-for="(event, index) in events"
...

<button ... @click="deleteEvent(index)"

And:

和:

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

回答by Afraz Ahmad

Don't forget to bind keyattribute otherwise always lastitem will be deleted

不要忘记绑定属性否则总是最后一项将被删除

Correct way to delete selected item from array:

从数组中删除所选项目的正确方法:

Template

模板

<div v-for="(item, index) in items" :key="item.id">
  <input v-model="item.value">
   <button @click="deleteItem(index)">
  delete
</button>

script

脚本

deleteItem(index) {
  this.items.splice(index, 1); \OR   this.$delete(this.items,index)
 \both will do the same
}

回答by Yevgeniy Afanasyev

It is even funnier when you are doing it with inputs, because they should be bound. If you are interested in how to do it in Vue2 with options to insert and delete, please see an example:

当你用输入来做这件事时,它甚至更有趣,因为它们应该被绑定。如果您对如何在 Vue2 中使用插入和删除选项进行操作感兴趣,请查看示例:

please have a look an js fiddle

请看看一个js小提琴

new Vue({
  el: '#app',
  data: {
    finds: [] 
  },
  methods: {
    addFind: function () {
      this.finds.push({ value: 'def' });
    },
    deleteFind: function (index) {
      console.log(index);
      console.log(this.finds);
      this.finds.splice(index, 1);
    }
  }
});
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
  <h1>Finds</h1>
  <div v-for="(find, index) in finds">
    <input v-model="find.value">
    <button @click="deleteFind(index)">
      delete
    </button>
  </div>
  
  <button @click="addFind">
    New Find
  </button>
  
  <pre>{{ $data }}</pre>
</div>

回答by Masum Billah

You can delete item through id

您可以通过 id 删除项目

<button @click="deleteEvent(event.id)">Delete</button>

Inside your JS code

在你的 JS 代码中

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 herefor more details.

Vue 包装了观察到的数组的变异方法,因此它们也会触发视图更新。单击此处了解更多详情。

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.

您可能认为这会导致 Vue 丢弃现有的 DOM 并重新渲染整个列表 - 幸运的是,事实并非如此。

回答by Claudio Scheuermann

<v-btn color="info" @click="eliminarTarea(item.id)">Eliminar</v-btn>

And for your JS:

对于您的 JS:

this.listaTareas = this.listaTareas.filter(i=>i.id != id)