为什么不总是在vue.js for loop中始终使用索引作为键?

JavaScript Vue.js

Gil达蒙

2020-04-03

我已经将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>

第3985篇《为什么不总是在vue.js for loop中始终使用索引作为键?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Mandy 2020.04.03

因为数组是可变的如果项目添加到数组中或从数组中删除,则任何给定项目的索引都可以并且将更改

您希望自己key成为唯一标识唯一组件的唯一值。您创建的主键总是比使用索引更好。

这是一个例子。

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.

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android