'What is <router-view :key="$route.fullPath">?
I'm completely new to Vue.js and I think I have a bit of understanding of how a router works with things like:
<router-link to="/">
But I am not really understanding what the following line does:
<router-view :key="$route.fullPath"></router-view>
I believe router-view
by itself makes sure the content is displayed but what does the key part mean?
Solution 1:[1]
It can also be used to force replacement of an element/component instead of reusing it. This can be useful when you want to:
- Properly trigger lifecycle hooks of a component
- Trigger transitions
$route.fullPath
is defined as
The full resolved URL including query and hash.
If you bind key
to $route.fullPath
, it will always "force a replacement" of the <router-view>
element / component every time a navigation event occurs.
As mentioned above, this is most probably done in order to trigger a transition / animation.
Solution 2:[2]
In Vue-Router 4.0, this is implemented using a scoped slot. According to the docs the following is necessary to force a route to reload.
<router-view v-slot="{ Component, route }">
<component :is="Component" :key="route.path" />
</router-view>
This is necessary for integrating with Vue 3 transitions.
<router-view v-slot="{ Component, route }">
<transition name="fade">
<component :is="Component" :key="route.path" />
</transition>
</router-view>
Note: Putting the :key="route.path"
directly on the <router-view>
can cause subtle routing issues. Such as a route with a redirect triggering twice.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Phil |
Solution 2 | Jayvin Chang |