Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom elements in iteration require 'v-bind:key' directives

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?

like image 980
drake035 Avatar asked Jun 06 '19 11:06

drake035


People also ask

Why do we need V-bind key?

You need the v-bind:key in a v-for because it needs to differentiate each component rendered, in case of data changing.

What is V-bind directive?

The v-bind directive is a Vuejs directive used to bind one or more attributes, or a component prop to an element. If that attribute is binded to our data defined in Vuejs instance then dynamically changes can be observed as data changes.

What is V-for in Vue?

v-for directive is a Vue. js directive used to loop over a data usually an array or object. First, we will create a div element with id as app and let's apply the v-for directive to an element with data.

Should be moved to the wrapper element?

This 'v-if' should be moved to the wrapper element. This error or warning occurs whenever you use both the v-for and v-if directive on the same HTML element. You might do so whenever you prefer to hide or not render the list based on a certain condition.


1 Answers

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>
like image 99
BTL Avatar answered Oct 06 '22 20:10

BTL