Vue patches with the virtual DOM whenever it is necessary. That is, whenever vue detects the changes on the DOM, it patches them for faster performance. And patching in the DOM will not change the icon or image. You need to replace the DOM instead.
Thus, vue provides the way for us whenever we need to change the DOM by replacing method, we can use :key
binding.
So, :key
binding can be used to force replacement of an element/component instead of reusing it.
The following whole html div will be replaced whenever there is change in favorite
data as we're :key
binding on 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 forcefully allows us to use :key
binding inside a loop as there's need of replacing the elements inside the loop whenever it detects the changes in the data
. This is made compulsory from 2.2.0+
and ESLint also have implemented this feature so that if you miss :key
binding inside the loop, then you'll see the error on that line when you use editor that supports eslint, so that you can fix the error.
Just an opinion, the strict requirement of the :key
binding should be removed from the vue as we might want a loop of predefined data
and don't want to change the DOM but we still use the v-for
loop for listing bigger data. But it might be rare case though.
Read carefully on the documentation for :key binding and then you'll have an idea.
The :key
binding can be useful when you want to:
Properly trigger lifecycle hooks of a component
Trigger transitions
- Use
:key
binding to replace the DOM. Remember it slower the performance as it replace the whole DOM that is bound to the element.
- Don't use
:key
binding when you don't want to replace the DOM or
you think there's no data
changes detection required. This will
allow vue to perform better without :key
binding.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…