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.
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.
v-if with v-for It's not recommended to use v-if and v-for on the same element due to implicit precedence.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With