How to deal with v-for in vuejs when element has n

2019-02-16 12:35发布

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.

标签: vuejs2
1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-16 13:24

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?

查看更多
登录 后发表回答