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

时间:2019-04-22 16:32:27

标签: vue.js key vue-component 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而不在最后一个元素下呈现分隔符吗?

2 个答案:

答案 0 :(得分:1)

这就是我生成密钥的方式-您可以自定义generateKey方法以返回所需的任何内容。

<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

答案 1 :(得分:0)

我正在和一个朋友聊天,他建议了最简单的解决方案,我认为是最好的解决方案。只需将组件前缀添加到每个键,例如:

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