vue实现多级路由
实现多级路由的基本配置
在 Vue Router 中,多级路由通过嵌套的 children 属性实现。在路由配置文件中,为父路由添加 children 数组,定义子路由的路径和组件。
const routes = [
{
path: '/parent',
component: ParentComponent,
children: [
{
path: 'child',
component: ChildComponent,
children: [
{
path: 'grandchild',
component: GrandChildComponent
}
]
}
]
}
]
路由视图的嵌套
父组件中需使用 <router-view> 作为子路由的出口。多级嵌套时,每一层父组件都需要包含 <router-view> 标签。
<!-- ParentComponent.vue -->
<template>
<div>
<h1>Parent Component</h1>
<router-view></router-view>
</div>
</template>
动态路由匹配
多级路由支持动态路径参数,通过 : 标记动态字段。子路由可继承父路由的动态参数。
{
path: '/user/:id',
component: User,
children: [
{
path: 'profile',
component: UserProfile // 访问路径为 /user/123/profile
}
]
}
路由重定向与别名
在嵌套路由中,可通过 redirect 实现默认子路由的自动跳转,或使用 alias 为路径设置别名。
{
path: '/parent',
redirect: '/parent/child', // 默认重定向到子路由
children: [
{
path: 'child',
alias: 'son', // 通过 /parent/son 也可访问
component: ChildComponent
}
]
}
路由守卫的应用
多级路由中,可通过 beforeEnter 或全局守卫实现权限控制。子路由会触发父路由的守卫。
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
// 父级路由守卫逻辑
},
children: [
{
path: 'dashboard',
component: Dashboard,
beforeEnter: (to, from, next) => {
// 子路由专属守卫
}
}
]
}
代码分割与懒加载
结合动态导入实现路由组件的懒加载,优化多级路由的性能。使用 import() 语法分割代码块。
{
path: '/lazy',
component: () => import('./LazyParent.vue'),
children: [
{
path: 'child',
component: () => import('./LazyChild.vue')
}
]
}
路径命名与编程式导航
为多级路由命名后,可通过 name 跳转。编程式导航支持传递多级路径参数。

// 路由配置
{
path: '/blog',
name: 'blog',
children: [
{
path: 'post/:id',
name: 'blog.post'
}
]
}
// 组件内跳转
this.$router.push({ name: 'blog.post', params: { id: 123 } })
注意事项
- 子路由的
path若以/开头会视为根路径,否则会相对父路径拼接 - 嵌套过深时建议拆分路由模块,维护独立配置文件
- 使用
router-link时注意to属性的完整路径拼接 - 可通过
v-if结合路由元信息 (meta) 控制嵌套路由的显隐逻辑






