Search code examples
vue.jskeyvue-componentv-for

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


I wanted to render a list using v-for. It's simple enough, the documentation explains almost every use case. I want it to look like that:

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

Unfortunately, the documentation does not say how to set a key for multiple custom components in one v-for.

Obviously, I don't want to include separator to my custom component, because it is used in other places too. Code I have pasted is generating those errors: 'template' cannot be keyed. Place the key on real elements instead. I can set a key on component and separator using an index but I got errors: Duplicate keys detected: 'x'. This may cause an update error.

For now, I'm doing it like that but it's an ugly hack and would not work with more components in one template.

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

Example from documentation explains templates on the list with basic components which does not require keys. Does anyone know how should I do it correctly?

Ps. It is not recommended to use v-if on v-for. Could someone suggest how to change my code not to use v-if but don't render separator under the last element?


Solution

  • I was talking with a friend and he suggested the simplest and in my opinion the best solution. Just add a component prefix to every key e.g:

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