32

In my Nuxt app I have the following line that triggers the error mentioned in the title of this question:

<template v-for="(project, index) in existingProjects">
    <span :key="project.projectId"></span>

I tried to have the :key attribute on the template element and I also tried to use just index as the key, to no avail.

Any idea?

2
  • 3
    You'd have to key all elements inside the template. If you have more than just the span, those elements would also need unique keys. Consider moving those elements into a component.
    – tony19
    Jun 6, 2019 at 11:49
  • May be use, looping (v-for) on a div instead of template and put keys then. Jun 6, 2019 at 11:52

1 Answer 1

51

There are multiple ways to solve your problem :

  1. You want to iterate on a template : You have to put a key on all elements in your template because you can not put a key on a template: <template> cannot be keyed. Place the key on real elements instead.
<template v-for="(project, index) in existingProjects">
    <span :key="project.projectId">foo</span>
    <div :key="project.projectId">bar</div>
</template>
  1. You can iterate on something else than a template : You just put the key on the parent html tag.
<div v-for="(project, index) in existingProjects" :key="project.projectId">
    <span>foo</span>
    <div>bar</div>
</div>
1
  • 4
    The first solution results in a warning Duplicate keys detected: 'ABC'. This may cause an update error. Can add a suffix like :key="project.projectId + '-span'" to make each key unique
    – lsowen
    May 17, 2020 at 17:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.