0

I have an array that is rendered as a set of Vue components using v-for. I need to use :key="" otherwise Vue complains.

My array has no unique identifiers so I use the index as the key

My loop

  <card v-for="(item, index) in questions" :question="item" :key="index">{{item}}</card> 

The array has objects that can have the same contents

[{name:"jimmy"}, {name:"billy bob"}, {name:"jimmy"}]

The problem: as soon as I manipulate the array the results become very unpredictable. Sometimes the components are rendered correctly. Sometimes a new component appears in the middle of the v-for list even though it was pushed into the array. Sometimes, after a shift / pop, all the old components remain and the newly pushed one doesn't appear.

Code

if(this.questions.length > 4) this.questions.shift()
this.questions.push({name:"willy jim"})

If I use item.name as the key, it works perfectly fine so long as there are no duplicate names. If I use item.name+index or something so silly, the whole thing goes bonkers...

Kokodoko
  • 26,167
  • 33
  • 120
  • 197
  • 2
    Possible duplicate of [Why not always use the index as the key in a vue.js for loop?](https://stackoverflow.com/questions/44531510/why-not-always-use-the-index-as-the-key-in-a-vue-js-for-loop) – Eric Guan Oct 08 '17 at 20:22

1 Answers1

1

Using the index as a key is a not a good idea as the index will recalculate when the array changes.

For example you might have something like this on the first render:

<div key="0">Item 1</div>
<div key="1">Item 2</div>
<div key="2">Item 3</div>
<div key="3">Item 4</div>

But, if you then change the array, say you remove the 2nd item, the index of each item will change so you end up with this:

<div key="0">Item 1</div>
<div key="1">Item 3</div>
<div key="2">Item 4</div>

...rather than:

<div key="0">Item 1</div>
<div key="2">Item 3</div>
<div key="3">Item 4</div>

If possible, it would be a good idea to give each item in your array an id and use that as the key instead:

[
  {
    id: 1,
    name:"jimmy"
  },
  {
    id: 2,
    name:"billy bob"
  },
  {
    id: 3,
    name:"jimmy"
  }
]
Steve Holgado
  • 11,508
  • 3
  • 24
  • 32