Reputation: 481
I have a Vue component called Layout
which contains two named views:
<template>
<router-view name="navigation"></router-view>
<router-view name="content"></router-view>
</template>
This is my router definition:
export default new Router({
routes: [
{
path: '/',
component: Layout,
children: [
{
path: '',
name: 'Login',
components: {
navigation: Navigation,
content: Login
}
}
]
},
{
path: '/dashboard',
component: Layout,
children: [
{
path: '',
name: 'Dashboard',
components: {
navigation: Navigation,
content: Dashboard
}
}
]
}
]
})
My Navigation
component has a specific logic that shows a different navigation bar depending on whether the user is logged-in or not and works perfectly.
In my Login
component I have an event handler that does the following:
this.$router.push({name: 'Dashboard'})
This line causes the Dashboard
view to replace the Login
view in the content
named view but the navigation
named view does not change and stays the same. The expected behavior is for it to be re-rendered and display different elements based on the new data.
The expected behavior does happen if I do a full page reload but not when a $router.push()
call is performed. I can't get to find what is that I'm doing wrong. How can I achieve the intended behavior?
Upvotes: 1
Views: 2096
Reputation: 481
According to the router documentation, this happens because once rendered, components are re-used and not parsed again. The Navigation
component is always rendered, so it's only parsed on its first appearance. The solution for this is to watch the $route
object, adding this code to the Navigation component causes it to be parsed appropriately:
watch: {
'$route' (to, from) {
if (from.name === 'Login' || from.name === 'Logout') {
this.generateNavigationLinks()
}
}
}
Upvotes: 1