I have a Main Navigation nav bar with some links. In the home page, i.e., in the root path ('/'), I have nested (child) routes.
Route configration:
const routes = [
{path: '/', component: HomeMainContent, children: [
{path: '', component: MovieList},
{path: 'in-theaters', component: MovieList},
{path: 'coming-soon', component: ComingSoonList},
{path: 'trailers', component: TrailerList},
]},
{path: '/about', component: About},
{path: '/contact',component: Contact},
];
So when the root path ('/') is active, its child router root path ('') is activated.
The template of child component router is in this way:
<template>
<div id="homeSubMenuWrapper">
<ul id="subMenuList">
<li v-for="menu in menuList">
<router-link class="menuItem" :to="menu.path">{{menu.name}}</router-link>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
menuList: [
{name: 'IN THEATER', path: '/in-theaters'},
{name: 'COMING SOON', path: '/coming-soon'},
{name: 'TRAILERS', path: '/trailers'},
]
}
}
}
</script>
Since, both the path ('') and ('in-theaters') have the same component, I would like to make the router-link of path ('in-theaters') to have the class of router-link-active whenever the child path ('') of its parent path ('/') is active. How can I do that?
Meaning the first child route ('in-theaters') should have the active class whenever the sub-route path is an empty path ('').
I would probably redirect from '/' to '/in-theaters'.
{path: '', beforeEnter: (to, from, next) => next('/in-theaters')},
If you'd be build a classic web app, you wouldn't create two routes to the same controller. I'd apply the same logic here.
A better approach would probably be to use an alias:
{path: ''`, alias: 'in-theatres', component: MovieList},
But currently that does not work either. We are tracking this here, though: #419
Would you be fine with closing your issue in favour of the existing one?
Hi,
Thank you guys for your help. Anyways, I ended up implementing checking of parent and child route path inside the template, like so.
<template>
<div id="homeSubMenuWrapper">
<ul id="subMenuList">
<li v-for="menu in menuList">
<router-link :class="[$route.fullPath ==='/' && menu.path === '/in-theaters' ? 'menuItem router-link-active' : 'menuItem']" :to="menu.path">{{menu.name}}</router-link>
</li>
</ul>
</div>
</template>
Hope this will help any noob like me.
I just use a redirect for the default child, to the specified path / name.
{
path: '/parent',
component: ParentComponent,
children: [
{
path: '',
name: 'parent',
redirect: { name: 'parent.childA' }
},
{
path: 'childA',
name: 'parent.childA',
},
{
path: 'childB',
name: 'parent.childB',
}
]
}
Most helpful comment
I just use a redirect for the default child, to the specified path / name.