如何使用 v-for 为模板标签中的组件设置多个键?

How to setup multiple keys for components in template tag using v-for?

我想使用 v-for 渲染一个列表。这很简单,文档解释了几乎每个用例。我希望它看起来像这样:

<template v-for="(item, index) in items" :key="index">
      <CustomComponent :item="item"/>
      <Separator v-if="index !== items.length-1"/>
</template>

遗憾的是,文档没有说明如何在一个 v-for 中为多个自定义组件设置键。

显然,我不想在我的自定义组件中包含分隔符,因为它也在其他地方使用。我粘贴的代码产生了这些错误: 'template' cannot be keyed. Place the key on real elements instead. 我可以使用索引在组件和分隔符上设置键,但出现错误:Duplicate keys detected: 'x'. This may cause an update error.

目前,我是这样做的,但这是一种丑陋的 hack,无法在一个模板中使用更多组件。

<template v-for="(item, index) in items">
      <CustomComponent :item="item" :key="(index+1)*-1"/>
      <Separator v-if="index !== items.length-1" :key="(index+1)"/>
</template>

文档中的示例使用不需要密钥的基本组件解释了列表中的模板。 有谁知道我应该如何正确操作?

Ps。不建议在 v-for 上使用 v-if。有人可以建议如何更改我的代码以不使用 v-if 但不在最后一个元素下呈现分隔符吗?

这是我生成密钥的方法——您可以根据需要自定义 generateKey 方法 return。

<template>
  <div>
    <div
      v-for="(item, index) in items"
      :key="generateKey(item, index)"
    >Item {{ index }} : {{ item }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: ["Sun", "Moon", "Stars", "Sky"]
    };
  },
  methods: {
    generateKey(item, index) {
      const uniqueKey = `${item}-${index}`;
      return uniqueKey;
    }
  }
};
</script>

工作示例:https://codesandbox.io/s/30ojo1683p

我和一个朋友聊天,他提出了最简单但在我看来是最好的解决方案。只需为每个键添加一个组件前缀,例如:

<template v-for="(item, index) in items">
      <CustomComponent :item="item" :key="'custom_component-'+index"/>
      <Separator v-if="index !== items.length-1" :key="'separator-'+index"/>
</template>