vue实现多级路由
Vue 多级路由实现方法
Vue Router 支持嵌套路由(多级路由),通过 children 配置实现层级关系。以下是具体实现方式:
路由配置
在 router/index.js 中定义嵌套路由结构:
const routes = [
{
path: '/parent',
component: ParentComponent,
children: [
{
path: 'child',
component: ChildComponent,
children: [
{
path: 'grandchild',
component: GrandChildComponent
}
]
}
]
}
]
路由视图渲染
父级组件需要包含 <router-view> 用于渲染子路由:
<!-- ParentComponent.vue -->
<template>
<div>
<h2>父级组件</h2>
<router-view></router-view>
</div>
</template>
动态路由匹配
可通过冒号 : 实现动态路径参数:

{
path: '/user/:id',
component: User,
children: [
{
path: 'profile',
component: UserProfile
}
]
}
命名路由
为路由设置 name 属性便于跳转:
{
path: '/settings',
name: 'settings',
component: Settings,
children: [
{
path: 'account',
name: 'settings.account',
component: AccountSettings
}
]
}
编程式导航
在组件中使用 $router 进行跳转:

this.$router.push('/parent/child/grandchild')
// 或使用命名路由
this.$router.push({ name: 'settings.account' })
路由守卫
可为嵌套路由设置导航守卫:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// 验证逻辑
}
next()
})
默认子路由
设置空路径作为默认渲染的子路由:
{
path: '/dashboard',
component: Dashboard,
children: [
{
path: '',
component: DashboardDefault
},
{
path: 'analytics',
component: DashboardAnalytics
}
]
}
实现多级路由时需注意:
- 路径拼接规则:子路由 path 会基于父路由 path 自动拼接
- 组件结构:每级路由对应的组件都需要包含
<router-view>容器 - 路由激活状态:可使用
router-link-exact-active类名设置样式






