Home > Blockchain >  How to use the key special attribute inside the v-for directive using an array of arrays
How to use the key special attribute inside the v-for directive using an array of arrays

Time:05-10

  1. List item

A have variable that contains an array of arrays of objects like this :

let FooVar: Array<Array<FooObject>> = [] ;

i want to loop through it inside a component something like this

<span v-for="item in FooVar" :key="XXX">

what should i put inside the key attribute ?

CodePudding user response:

As said in the documentation

The key special attribute is primarily used as a hint for Vue's virtual DOM algorithm to identify vnodes when diffing the new list of nodes against the old list.

It will also be used for

  • Properly trigger lifecycle hooks of a component
  • Trigger transitions

The only requirements is that your keys must not have any duplicates

Children of the same common parent must have unique keys. Duplicate keys will cause render errors.


In general the best way is by adding an unique identifier to the item with for example an id comming from the database

<span v-for="item in FooVar" :key="item.id">

If you don't have any id, then you can use the index of the item in the list.

Note that this is NOT optimzed and see here why

<span v-for="(item, index) in FooVar" :key="index">

CodePudding user response:

You can put index:

<span v-for="(item, index) in FooVar" :key="index">
  • Related