0

I am using Vue v-for for iterating over an array, like:

<div v-for="item in items">
    {{ item }}
</div>

Vue tells me to have a key and recommends me to take a look at the Docs: key.

Does that make sense to put the index in the :key?

Example:

<div v-for="(item, index) in items" :key="index">
    {{ item }}
</div>
tony19
  • 125,647
  • 18
  • 229
  • 307
Vince Varga
  • 6,101
  • 6
  • 43
  • 60

2 Answers2

0

If you Item is an object with an id prop then it would be best to use that.

In small scale applications where you are sure your data has no chance of duplication i would use a name or id prop from the object mixed with the index e.g

<div v-for="(item, index) in items" :key="`${item.id}-${index}`">

or

<div v-for="(item, index) in items" :key="`${item.name}-${index}`">
Francis Leigh
  • 1,870
  • 10
  • 25
  • What advantage does adding the `item` to the key bring here? – Vince Varga Feb 05 '18 at 15:06
  • I mean, why is it better than just simply using `index` as key? – Vince Varga Feb 05 '18 at 15:06
  • It is fine to use the `index` but with previous experience with an Angular 1.5 project, when manipulating an arrays order it threw a few errors. that is why i go one step further to append an `id` or `name` to the front of the iteration key. – Francis Leigh Feb 05 '18 at 15:09
0

Using index as a key is an anti-pattern

What happens if you push an item to the list or remove something in the middle? If the key is same as before [Vue] assumes that the DOM element represents the same component as before. But that is no longer true.

Roy J
  • 42,522
  • 10
  • 78
  • 102
  • This is definitely true when rendering components via `v-for`. But is there any reason to not use the index as the key when just rendering html elements like in OP's example? – thanksd Feb 05 '18 at 15:35
  • 1
    I don't think there's a reason to explicitly use `index` as the `key`. Just ignore the warning. (I don't even get a warning using the above example in a snippet with no key.) – Roy J Feb 05 '18 at 15:46
  • huh, yeah I see now that I don't get a Vue warning either. My intellisense plugin for vue yells at me though, and I use `index` as `key` to get rid of the ugly red lines. – thanksd Feb 05 '18 at 15:51