sen*_*nty 4 javascript arrays splice array-splice vuejs2
我有一个列表,并且正在使用for循环遍历它。结构如下:
salesLists: {
1: [ [], [], [] ]
2: [ [], [] ]
}
Run Code Online (Sandbox Code Playgroud)
和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>
Run Code Online (Sandbox Code Playgroud)
现在,我正在尝试从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()
}
Run Code Online (Sandbox Code Playgroud)
但是,它删除了它,因为我没有指定任何键,并且它只是空数组(我认为),所以没有从DOM中删除正确的元素。它删除了索引2,但是当它v-for遍历该项目并减少计数时,它仅删除了最后一个项目。
解决此问题的正确方法是什么?:/
这是一个小提琴:https : //jsfiddle.net/8rvfz40n/ 尝试为每个输入字段编写不同的值并删除中间的一个,您将看到它将删除最后一个
Run Code Online (Sandbox Code Playgroud)<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为null。
我使用的哈希是一个时间戳:
Hash: new Date().getTime()
Run Code Online (Sandbox Code Playgroud)
然后:
<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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3653 次 |
| 最近记录: |