Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with v-for in vuejs when element has no id?

Tags:

vuejs2

I often get this error related to the v-for directive.

Elements in iteration expect to have v-bind:key directive

When using a for loop like this.

<div v-for='person in people'> {{ person.name }} </div>

The problem is, in sometimes in rare cases, I have no id key for person. And I want to know what can be done in this case.

like image 509
hidar Avatar asked Oct 04 '17 12:10

hidar


People also ask

Why is it recommended not to use V-if and V-for directives together on the same element in VUE JS?

The problem with this is that VueJS prioritizes the v-for directive over the v-if directive. So under the hood, it loops through every element and THEN checks the v-if conditional. This means that even if we only want to render a few elements from a list, we'll have to loop through the entire array.

Can we use V-if with V-for?

v-if with v-for It's not recommended to use v-if and v-for on the same element due to implicit precedence.

How does v-If work Vue?

v-if - Only renders the element to the DOM if the expression passes. v-show - Renders all elements to the DOM and then uses the CSS display property to hide elements if the expression fails. v-show - Does not support v-else , v-else-if.

Can I use index as key Vue?

No indexes as keys You should not use array indexes as keys since indexes are only indicative of an items position in the array and not an identifier of the item itself.


1 Answers

As Ghanshyam already mentioned in comments, you can easily generate an index in v-for.

<div v-for="(person, index) in people" :key="index" >
    {{ person.name }}
</div>

However, there is something to be said for NOT using index as a key.

Other SO Post: Why not always use the index as the key in a vue.js for loop?

like image 84
Kyle Holmberg Avatar answered Oct 19 '22 19:10

Kyle Holmberg