Reputation: 5176
I have this simple component that has a person
with values that it should display:
TestFor.vue:
<template>
<div v-for = "(value, key) in this.person">
{{key}} : {{value}}
</div>
</template>
<script scoped>
export default {
props: {
person: {
firstName: 'Bob',
lastNmae: 'Andersen',
age: 27
}
}
}
</script>
However I get the Elements in iteration expect to have 'v-bind:key' directives vue/require-v-for-key
error. Which shouldn't occur, because according to documentation: https://v2.vuejs.org/v2/guide/list.html my syntax is valid:
This video tutorial also uses this syntax and it works fine for them. Why doesn't it work for me?
EDIT:
As people have said the require-v-for-key
rule is a culprit. Is there any reason behind that rule or is it OK to just disable it?
I've added "vue/require-v-for-key": "off"
to package.json
and the original code seems to be working now. Am I good or should I enable that rule back? It just seems like an annoyance for no reason.
Upvotes: 2
Views: 1641
Reputation: 44715
You need to define key per element of your list. in your case, it's quite trivial:
<div v-for = "(value, key) in this.person" :key='key'>
{{key}} : {{value}}
</div>
Without the key, Vue is unable to link data to components created with v-for. Lack of key means that any modification of the object you iterated would destroy and recreate all the child components, which would bring a number of undesired side effects. Once the key is defined, when collection changes, vue will calculate key for each element, compare it with keys of existing children and act accordingly.
Upvotes: 3
Reputation: 1003
The error means you need to bind the key property at your div.
<template>
<div v-for = "(value, key) in person" :key="key">
{{key}} : {{value}}
</div>
</template>
<script scoped>
export default {
props: {
person : {
type : Object,
default : function(){
return {
firstName: 'Bob',
lastNmae: 'Andersen',
age: 27
}
}
}
}
}
}
</script>
Upvotes: 2
Reputation: 206
The error is coming from your linter rule: require-v-for-key
You can fix it, with adding the key binding:
<div v-for = "(value, key) in this.person" :key="key">
{{key}} : {{value}}
</div>
Upvotes: 3