Vue patches with virtual DOM whenever needed. That is, whenever vue detects changes in the DOM, it patches them to improve performance. And a fix in the DOM will not change the icon or image. Instead, you need to replace the DOM.
Thus, vue provides us with a way when we need to change the DOM, replacing the method, we can use the binding :key .
So, the binding :key can be used to force the replacement of an element / component instead of reusing it.
The following entire html div will be replaced whenever there is a change in favorite , since we :key bind to it:
<div :key="favorite"> <a v-on:click="toggleFavorite" style="cursor: pointer"> <i v-show="favorite" class="text-warning fas fa-star"></i> <i v-show="!favorite" class="text-warning far fa-star"></i> </a> </div>
This is why vue forcibly allows us to use the binding :key inside the loop, since it is necessary to replace the elements inside the loop whenever it detects changes in data . This is mandatory for 2.2.0+ , and ESLint also implements this function so that if you miss the :key binding inside the loop, then you will see an error on this line when you use an editor that supports eslint so that you can fix the error.
Just an opinion, a strict binding requirement :key must be removed from vue, because we may need a predefined data loop and don't want to change the DOM, but we still use the v-for loop to list big data. But this may be a rare case.
Read the documentation carefully for: key bindings , and then you get an idea.
Binding :key can be useful if you want:
Properly run component lifecycle hooks
Trigger transitions
- Use
:key binding to replace the DOM. Remember that this is a slower performance since it replaces the entire DOM associated with the element. - Do not use the
:key binding if you do not want to replace the DOM or you think that there is no need to detect changes to data . This will let vue work better without binding :key .