Why is the :key attribute needed in vuejs v-for?

Viewed 3716

my vscode is complaning that I need this attribute in my vuejs v-for as in

BAD

<p v-for='person in people'> {{person.name}} </p>

GOOD

<p v-for='(person, index) in people' :key='index'> {{person.name}} </p>

So, why do we need :key attribute?

2 Answers

Suppose we have list of items in an array.

v-for

If we use v-for it will show all those items based on their index. VueJs doesn't keep track of all those elements. Whenever any changes are made in the items the VueJs will just replaces the positions in dom according to the indexes of items in an array.(just replaces instead of moving elements) It just patches up or replaces the positions(in dom). It doesn't store any values of items of an array.It doesn't track the values of items. It only stores index positions.

The problem with this is sometimes any changes made in the array of items vuejs can't update according our needs.(Remember in some cases). What if we want our vuejs to keep track those items inside an array. That's where :key comes in the picture.

:key

Now when we mention key attribute(like item.id etc.,.) in v-for vuejs will have direct reference to those items. Remember now vuejs instead of storing positions it will store the items. Vuejs will keep track of all those items inside an array. Whenever any changes made in the items now it will change those items in the dom.(By moving elements in dom) :key just makes sure that vuejs is keeping track of all those items.(every key attribute acts like an id. Whenever something changes vuejs will always takes the updated value.)

As a end user we don't see the difference much in output(if we don't mention :key) but in the background above things will happen.

Go through this you will definitely find the difference. Controlling Reusable Elements with key

As pointed out by thanksd: It is required for vue components when using vue 2.2.0+ :

In 2.2.0+, when using v-for with a component, a key is now required.

Original answer:

As it is said in Vue.js official guide:

To give Vue a hint so that it can track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique [...] It is recommended to provide a key with v-for whenever possible, unless the iterated DOM content is simple, or you are intentionally relying on the default behavior for performance gains.

You don't need a key attribute in order to use v-for, but it's a good practice, that's why VScode's intelliSense is telling you to add one.

Related