[英]Using .splice to remove an item from an array is removing multiple objects
[英]Remove item from array using splice
我正在使用Vue JS,我有2個不同的數組categories
和items
。 每個項目都可以屬於多個類別,這些項目是動態生成的,因此最初不在類別數組中關聯。 然后,我分析類別數組以創建包含不同項目的表。
出於測試目的,我將這些項附加到已掛載的vue屬性中與其關聯的類別,如下所示:
mounted: function() {
for (let item of this.items) {
for (let category of item.categories) {
this.categories[category - 1].items.push(item)
}
}
}
然后按下刪除按鈕時,我觸發deleteItem
它使用拼接,以刪除的項目方法categories
排列,並從items
陣列為好,但我有一個小問題上有正確的項目不會被刪除。
methods: {
deleteItem: function(item) {
for (let category of item.categories) {
this.categories[category - 1].items.splice(this.categories[category - 1].items.indexOf(item, 1))
}
this.items.splice(this.items.indexOf(item, 1))
}
}
請參閱示例Fiddle 。 任何幫助將不勝感激。
更改
this.items.splice(this.items.indexOf(item, 1))
至
this.items.splice(this.items.indexOf(item), 1)
這樣就可以將1
作為第二個參數傳遞給splice
。
請注意,您兩次執行相同的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.