如何用实现多级子菜单和没有子菜单的路由在router-view中跳转在Menu菜单中一起实现
时间: 2023-12-14 20:38:37 浏览: 25
要实现多级子菜单和没有子菜单的路由在`router-view`中跳转,在`Menu`菜单中一起实现,可以按照以下步骤操作:
1. 在路由配置中定义多级子路由和没有子路由的路由。例如:
```javascript
const routes = [
{
path: '/',
redirect: '/home'
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About,
children: [
{
path: '',
component: AboutHome
},
{
path: 'company',
component: Company
},
{
path: 'team',
component: Team
}
]
},
{
path: '/contact',
component: Contact
}
];
```
2. 在`Menu`菜单中使用`v-for`指令循环遍历路由配置,根据路由是否有子路由来渲染不同样式的菜单项。例如:
```html
<template>
<div class="menu">
<ul>
<li v-for="route in routes" :key="route.path">
<router-link :to="route.path" :class="{ active: isRouteActive(route) }">
{{ route.meta.title }}
</router-link>
<ul v-if="route.children">
<li v-for="child in route.children" :key="child.path">
<router-link :to="child.path" :class="{ active: isRouteActive(child) }">
{{ child.meta.title }}
</router-link>
</li>
</ul>
</li>
</ul>
</div>
</template>
```
3. 在`Menu`菜单中定义`isRouteActive`方法,用于判断当前路由是否处于激活状态。例如:
```javascript
methods: {
isRouteActive (route) {
return this.$route.path === route.path || this.$route.path.startsWith(`${route.path}/`);
}
}
```
4. 在主应用中引入`Menu`菜单和`router-view`组件,并使用`router-view`组件来渲染路由组件。例如:
```html
<template>
<div class="app">
<Menu :routes="routes" />
<router-view />
</div>
</template>
<script>
import Menu from './components/Menu.vue';
import routes from './routes';
export default {
components: {
Menu
},
data () {
return {
routes
};
}
};
</script>
```
这样就可以实现多级子菜单和没有子菜单的路由在`router-view`中跳转,在`Menu`菜单中一起实现了。