Using keys properly of loops in Vue

Tram Ho

1. v-for & key

A small example of loop in vue

result

Now I will add a function to reverse the array items

After clicking the button reserve then the array has been reversed and displayed correctly

But if you open inspect and look at id of cards <p> then the position of the cards is not reversed, only the value changes

The reason why we can easily find on Vue’s docs

When Vue is updating a list of elements rendered with v-for, by default it uses an “in-place patch” strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, Vue will patch each element in-place and make sure it reflects what should be rendered at that particular index. This is similar to the behavior of track-by=”$index” in Vue 1.x.

Simply put, when the list is updated, Vue will use the “in-place patch” method by default. If the order of the elements in the array is changed, Vue will update the values on the DOM elements to make sure they are displayed correctly, not move them in the new order.

Not moving the DOM can cause unexpected errors when you’re working with a form, for example. To make it easier to understand, I will make another example. First I will create a new component CustomInput

Then I will edit the original file with an example of a loop

Now try to enter some information and press the button reserve. Here are the results before and after pressing the button.

The title of the input has changed but the value doesn’t match, because the components are not reordered, only the input value is updated.

So that the components can be rearranged in a new order, let’s add key into the loop. Edit the code a bit

Unfortunately, the index is useless in this case, because when you reverse the position of the element in the array, the index is still rendered in order => the key is changed => not unique. What we need key is that it must be unique and primitive. In most cases, using the index as a key is useless, so in my personal opinion, you should be careful when using the index as a key.

2. Solution using key for simple array

For the case of a simple array like the example above, you should always use the value of the element as the key (make sure no elements are duplicate). If it’s an array of objects, use lib object-hash + computed to generate keys for elements. In case of duplicate elements, generate a key for each element using the random algorithm.

Share the news now