我有一个列表,我正在使用 for 循环遍历它。结构如下所示:
salesLists: {
1: [ [], [], [] ]
2: [ [], [] ]
}
和 html:
<div v-for="(saleLists, index) in salesLists">
<my-comp v-for="(item, i) in saleLists" :key="i" :index="parseInt(i)+1"></my-comp>
</div>
现在,我正尝试从 salesLists[1]
数组中删除项目。我有一个按钮和 @click="removeForm"
:
removeForm(e) {
var index = parseInt(e.target.getAttribute('data-index')) - 1 // = 2
var client = e.target.getAttribute('data-client') // = 1
//Vue.delete(this.salesLists[client], index);
this.salesLists[client].splice(index, 1)
this.$forceUpdate()
}
但是,它删除了它,因为我没有指定任何键并且它只是空数组(我假设),它没有从 DOM 中删除正确的元素。它删除了 2 的索引,但由于它是 v-for
循环遍历该项目,并且计数减少,它最后只删除最后一个项目。
克服这个问题的正确方法是什么? :/
这是一个 fiddle :https://jsfiddle.net/8rvfz40n/ 尝试为每个输入字段写入不同的值并删除中间的值,您会看到它会删除最后一个值
最佳答案
<div v-for="(saleLists, index) in salesLists"> <my-comp v-for="(item, i) in saleLists" :key="i" :index="parseInt(i)+1"></my-comp> </div>
使用索引作为键是个问题,当你从中间删除一个项目时,丢失的索引是最后一个。
在我的例子中,我找到的解决方案是为项目添加一个唯一的“哈希”,例如 ID,但如果项目是新闻,则 ID 为空。
我使用的散列是时间戳:
Hash: new Date().getTime()
然后:
<div v-for="(saleLists, index) in salesLists">
<my-comp v-for="(item, i) in saleLists" :key="item.Hash" :index="parseInt(i)+1"></my-comp>
</div>
关于javascript - Vue array.splice 从列表中删除错误的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45655090/