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

Vue.js 如何使用v-for为模板标记中的组件设置多个键?,vue.js,key,vue-component,v-for,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 v-for="(item, index) in items" :key="index">
      <CustomComponent :item="item"/>
      <Separator v-if="index !== items.length-1"/>
</template>
文档中的示例解释了列表中包含不需要键的基本组件的模板。 有人知道我该怎么做吗


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

以下是我如何生成密钥的方法--您可以自定义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>

项目{{index}}:{{Item}
导出默认值{
数据(){
返回{
物品:[“太阳”、“月亮”、“星星”、“天空”]
};
},
方法:{
generateKey(项目、索引){
const uniqueKey=`${item}-${index}`;
返回唯一键;
}
}
};

工作示例:

我与一位朋友交谈,他提出了最简单的解决方案,我认为这是最好的解决方案。只需为每个键添加组件前缀,例如:

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

我认为情况并非如此。因为为什么我要为分隔符生成一个特殊的键?分隔符永远不会更新,它完全取决于在其上方呈现的项目。
<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>