为什么不总是使用索引作为vue.js for循环中的键? [英] Why not always use the index as the key in a vue.js for loop?

查看:539
本文介绍了为什么不总是使用索引作为vue.js for循环中的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将vue.js用于了几个项目,并且我一直使用索引作为for循环中的键

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>

...并开始怀疑是否存在问题,因为示例通常使用ID条目:key =item.ID中的项目。

...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.

您想要 key 是一个唯一值,仅标识您的唯一组件。您创建的主键总是比使用索引更好。

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.

以下是一个示例。

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>

请注意,单击 addValue ,顶部的列表表示数组中真正在数组中的新数字;在中间。在按钮下方的第二个列表中, not 的值表示数组中的实际位置,而内部和属性值同意。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆