在 v-for 中使用哪个键

Which key to use in v-for

我正在用一个数组填充一个下拉列表,但是我不知道应该在 v-for 中使用哪个键。

我试过多个钥匙,甚至没有钥匙。似乎一切正常,但最佳做法是什么?

<select class="period-control" v-model="selected">
<option v-for="month in car.months" :key="month.id">{{ month }}</option>
</select>



asyncData(context) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({
          car: [
            {
              id: "1",
              brand: "VW",
              model: "Transporter",
              variant: "Sport",
              thumbnail:
                "http://pluspng.com/img-png/cargo-van-png-van-png-transparent-image-1878.png",
              mprice: "2700",
              dpayment: "5400",
              months: [
                { month: "12 måneder" },
                { month: "24 måneder" },
                { month: "36 måneder" }
              ]
            },
            {
              id: "2",
              brand: "Nissan",
              model: "Tekna",
              variant: "Sport",
              thumbnail:
                "http://pluspng.com/img-png/cargo-van-png-van-png-transparent-image-1878.png",
              mprice: "3000",
              dpayment: "5400",
              months: ["12 måneder", "24 måneder"]
            }
          ].find(el => el.id === context.params.id)
        });
      }, 1500);
    });
  }

Ì 没有错误,下拉列表正在输出正确的数组。

'best practice' 要求您使用唯一的密钥。在您的情况下,您可以使用数组中每个元素的 id。这样做的原因是,它允许 vue 跟踪 dom 和虚拟 dom 之间的所有元素,以防它们中的任何一个被删除。

作为最后的手段,您也可以使用项目的索引,但请记住,这可能会导致一些渲染问题,因为 vue 会发现很难唯一标识元素并跟踪已删除的元素.

When Vue is updating a list of elements rendered with v-for, by default it uses an “in-place patch” strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, Vue will patch each element in-place and make sure it reflects what should be rendered at that particular index. This is similar to the behavior of track-by="$index" in Vue 1.x.

This default mode is efficient, but only suitable when your list render output does not rely on child component state or temporary DOM state (e.g. form input values).

To give Vue a hint so that it can track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item:

https://vuejs.org/v2/guide/list.html#Maintaining-State