为什么不总是使用索引作为 vue.js for 循环中的键? [英] Why not always use the index as the key in a vue.js for loop?
问题描述
我在几个项目中使用了 vue.js,并且我一直使用索引作为 for 循环中的键
<div v-for="(item, index) in items" :key="index"></div>
...并且开始怀疑这是否存在问题,因为示例通常使用项目的 ID.
<div v-for="(item, index) in items" :key="item.ID"></div>
因为数组是可变的.如果项目被添加到数组或从数组中删除,任何给定项目的索引可以并且将会改变.
您希望您的 key
是一个唯一值,仅标识您的唯一组件.您创建的主键总是比使用索引更好.
这是一个例子.
console.clear()Vue.component("项目", {道具:[价值"],数据() {返回 {内部值:this.value}},模板:`<li>内部:{{internalValue}} 道具:{{value}}</li>`})新的 Vue({el: "#app",数据: {项目:[1, 2, 3, 4, 5]},方法: {添加值(){this.items.splice(this.items.length/2, 0, this.items.length + 1)}}})
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"><;/脚本><div id="应用程序">{{项目}}<ul><item v-for="i in items" :value="i" :key="i"></item><button @click="addValue">AddValue</button><ul><item v-for="(i, index) in items" :value="i" :key="index"></item>
注意,当点击addValue
时,最上面的列表代表数组中真正在数组中的新数字;在中间.在按钮下方的第二个列表中,值不代表数组中的实际位置,并且内部值和属性值不一致.
I have used vue.js for a couple of projects and I have been using the index as the key in the for loops
<div v-for="(item, index) in items" :key="index"></div>
...and have started to wonder if there are problems with that since examples usually use the ID of the item.
<div v-for="(item, index) in items" :key="item.ID"></div>
Because arrays are mutable. The index of any given item can and will change if items are added to or removed from the array.
You want your key
to be a unique value identifying only your unique component. A primary key that you create is always better than using an index.
Here is an example.
console.clear()
Vue.component("item", {
props: ["value"],
data() {
return {
internalValue: this.value
}
},
template: `<li>Internal: {{internalValue}} Prop: {{value}}</li>`
})
new Vue({
el: "#app",
data: {
items: [1, 2, 3, 4, 5]
},
methods: {
addValue() {
this.items.splice(this.items.length / 2, 0, this.items.length + 1)
}
}
})
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
{{items}}
<ul>
<item v-for="i in items" :value="i" :key="i"></item>
</ul>
<button @click="addValue">AddValue</button>
<ul>
<item v-for="(i, index) in items" :value="i" :key="index"></item>
</ul>
</div>
Note that when addValue
is clicked, the list on top represents the new numbers in the array where the truly are in the array; in the middle. In the second list below the button, the values do not represent the actual location in the array and the internal and property values do not agree.
这篇关于为什么不总是使用索引作为 vue.js for 循环中的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!