The key attribute in Vue
When updating a list of elements rendered by the v-for directive, Vue uses an in-place update strategy by default. If the order of the array or object elements has changed, Vue will not move the DOM elements, but will simply update each element in-place to reflect the new data at the corresponding index.
To tell Vue how to determine the identity of each element, and thus reuse and order existing elements, you need to specify a unique key attribute for each element.
Without keys, Vue uses an algorithm that minimizes element movement and tries to change as much as possible./reuse elements of the same type. When using keys, elements will be reordered according to the change in the order of the keys, and elements whose keys are no longer present will always be removed/be destroyed.
It is recommended to always specify the key attribute with v-for unless the DOM content being iterated over is simple, or you are deliberately relying on the default update strategy for performance reasons.
As a rule, the question of adding keys arises when iterating over an array of objects. In this case, one of the object's keys is a unique field, for example, id:
data() {
return {
users: [
{
id: 1,
name: 'name1',
surn: 'surn1',
},
{
id: 2,
name: 'name2',
surn: 'surn2',
},
{
id: 3,
name: 'name3',
surn: 'surn3',
},
]
}
}
Let's iterate over the given array using a loop, specifying the corresponding keys:
<template>
<p v-for="user in users" :key="user.id">
{{ user.name }}
{{ user.surn }}
</p>
</template>
Loop through the following array and print the product names as a list of ul:
data() {
return {
products: [
{
id: 1,
name: 'product1',
},
{
id: 2,
name: 'product2',
},
{
id: 3,
name: 'product3',
},
]
}
}