How to implement sub menu of the current route's children with vue.js and vue router
You don't need to create new router instances, instead watch the $route
property and create the sidebar nav menu as it changes. You'll need to pull the child routes from the $router.options.routes
. Here's an example:
const router = new VueRouter({
routes: [{
name: 'home',
path: '/',
component: {
template: '<div>Home</div>'
}
},
{
name: 'foo',
path: '/foo',
component: {
template: '<div>Foo<router-view></router-view></div>'
},
children: [{
name: 'foo.baz',
path: '/baz',
component: {
template: '<div>Baz</div>'
}
}, {
name: 'foo.tar',
path: '/tar',
component: {
template: '<div>Tar</div>'
}
}]
},
{
name: 'bar',
path: '/bar',
component: {
template: '<div>Bar<router-view></router-view></div>'
},
children: [{
name: 'bar.zim',
path: '/zim',
component: {
template: '<div>Zim</div>'
}
}, {
name: 'bar.zug',
path: '/zug',
component: {
template: '<div>Zug</div>'
}
}]
}
]
})
new Vue({
el: '#app',
router,
data() {
return {
children: []
}
},
watch: {
$route: function(current) {
const route = this.$router.options.routes.find(route => route.path === current.path)
if (route && Array.isArray(route.children)) {
this.children = route.children
} else if (route) {
this.children = []
}
}
}
})
* {
margin: 0;
padding: 0;
}
html,
body,
#app {
width: 100%;
height: 100%;
}
#top {
border: 1px solid black;
}
#top ul {
display: flex;
flex-direction: row;
justify-content: flex-start;
list-style-type: none;
}
li {
padding: 1rem;
text-align: center;
text-transform: uppercase;
}
li a {
text-decoration: none;
font-weight: bold;
color: black;
}
#sidebar {
height: 50%;
width: 100px;
border: 1px solid black;
}
#content {
width: 50%;
}
#content,
#content>div {
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<div id="top">
<ul>
<li v-for="item in $router.options.routes" :key="item.path" :style="{ 'background-color': $route.name.includes(item.name) ? 'rgba(197,225,165,1)' : 'white' }">
<router-link :to="item.path">{{ item.name }}</router-link>
</li>
</ul>
</div>
<div style="display: flex; flex-direction: row; height: 100%; width: 100%;">
<div id="sidebar">
<ul>
<li v-for="item in children" :key="item.path" :style="{ 'background-color': $route.name === item.name ? 'rgba(197,225,165,1)' : 'white' }">
<router-link :to="item.path">{{ item.name.split('.').pop() }}</router-link>
</li>
</ul>
</div>
<div id="content">
<router-view></router-view>
</div>
</div>
</div>