3👍
What’s the key
attribute
The purpose of the special :key
prop is to give hints to Vue about which element is which component. It’s used to inform the framework how the dom element is linked to the Vue component instance (or "vnode").
It’s mainly useful in the cases of v-for
, Transition
and some other edge cases. So Vue can tell which element has been moved / changed / removed etc, and then optimize what component should be mounted, re-rendered or unmounted.
Here’s the official documentation of the "key" attribute
Using key
on static components?
Whenever the key
of a component changes, you’re basically telling Vue that this is not the same component instance: your Component_2
was binded to the key 0
, but after the click, it sees the key 1
.
It compares the vnodes it had before and the new ones and says "oh ok, component 0
has been removed, and component 1
has been added, I should unmount the former and mount the latter.
In this case, it doesn’t make much sense to use key
on a static component. Even less to update the key value when your component doesn’t change at all.
You should use it only in specific cases where you really want Vue to trigger a re-rendering of your component when something happens.
1👍
:key
is a tool which gives more precise control over a component’s lifecycle.
By default Vue optimises DOM rendering and, wherever possible, it reuses existing DOM elements when data changes.
There are cases when you want to tell Vue either one of:
- although I’m using the same component, this instance is different than the old one or…
- although this component has changed its position in DOM, it’s the same as one previously rendered, you can simply move it here instead of creating it from scratch. By keeping the
key
the same you make sure the animation associated with adding/removing to/from DOM of an element is played when the element is actually added/removed and not when it changes its position in the parent.
Most importantly, when the key
changes, the old component is unmounted and gets destroyed, and the new one is created and mounted, so any code placed in the associated lifecycle hooks will get run accordingly, whereas if the key
does not change, those hooks won’t be (re-)run. Only beforeUpdate
and updated
will be run.
Another example: key
comes in handy when you’re rendering a route component and you want certain data to be fetched when the component’s route mounts. If you don’t change the key
, even though the params of the route change, the data required for the page won’t get fetched (if its fetched in mounted
, beforeMount
or created
).