Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Error "Elements in iteration expect to have 'v-bind:key' directives vue/require-v-for-key" in index.vue

I am new to vue.js. I have a simple index.vue which tries to connect to contentful and display the entries from contentful. My code in index.vue looks like this:


<template>
  <div>
    <!-- render data of the person -->
    <h1>{{ person.fields.name }}</h1>
    <!-- render blog posts -->
    <ul>
      <li v-for="post in posts">
        {{ post.fields.title }}
      </li>
    </ul>
  </div>
</template>

<script>
  import {createClient} from '~/plugins/contentful.js'

  const client = createClient()

However when I try localhost:3000 from my browser...it comes back with the following error:


ERROR in ./pages/index.vue Module Error (from ./node_modules/eslint-loader/index.js):

C:\Users\admin\pdress\pages\index.vue 7:7 error Elements in iteration expect to have 'v-bind:key' directives vue/require-v-for-key

✖ 1 problem (1 error, 0 warnings)


I appreciate if someone can help me out to proceed further with my learning on vue.js please. Thanks in advance

like image 469
user2368975 Avatar asked Jan 17 '19 02:01

user2368975


2 Answers

What @ljubadr suggested is right. You need to do this:

<li v-for="post in posts" v-bind:key="post.id">

<!-- OR USE SHORTCUT NOTATION -->
<li v-for="post in posts" :key="post.id">

The reason has to do with performance. Attribute key helps Vue determine unique items in a list. Consider the example of sorting. If your UI has a sort button for posts, then your the order of items in post array will change. But does that mean Vue is going to re-render entire list? Of course not! Using :key it can determine if the item was already rendered on UI. It simply shuffles the DOM nodes and saves expensive rendering cycles.

Secondly, if you have complex components within your list when you are using v-for and :key is not provided, then whenever the list is changed or re-ordered, it simply changes the DOM but doesn't destroy existing components and that can cause local state mismatch. That is why it is must to have :key attribute.

Read Vue.js documentation for further information.

Note: Also remember that using v-for index for :key is a bad idea as it is not unique across your collection.

like image 71
Harshal Patil Avatar answered Oct 02 '22 11:10

Harshal Patil


You must define a :key atribute for

v-for directive. And for <transition-group> tag.

for this case v-for you must explicit set,

  <li v-for="(post, i) in posts" :key="i + 10">
    {{ post.fields.title }}
  </li>

If you noticed you can define max two argument in the v-for you must define the item (post) and can define the index of the post.

like image 43
Yoarthur Avatar answered Oct 02 '22 11:10

Yoarthur