vue路由嵌套实现
路由嵌套的实现方式
在Vue中,路由嵌套通过children属性实现,允许在父路由下定义子路由,形成层级结构。以下是具体实现步骤:
定义嵌套路由配置
在路由配置文件(通常为router/index.js)中,通过children属性定义嵌套路由:
const routes = [
{
path: '/parent',
component: ParentComponent,
children: [
{
path: 'child',
component: ChildComponent
},
{
path: 'another-child',
component: AnotherChildComponent
}
]
}
]
父组件中放置路由出口
父组件模板中需包含<router-view>标签,作为子路由的渲染出口:

<!-- ParentComponent.vue -->
<template>
<div>
<h2>父组件</h2>
<router-view></router-view>
</div>
</template>
子路由访问路径
嵌套路由的完整路径由父路径和子路径拼接而成:
/parent/child访问ChildComponent/parent/another-child访问AnotherChildComponent
默认子路由设置
可通过redirect或空路径设置默认子路由:

children: [
{
path: '',
component: DefaultChildComponent
}
]
动态路由嵌套
支持在嵌套路由中使用动态参数:
{
path: '/user/:id',
component: UserLayout,
children: [
{
path: 'profile',
component: UserProfile
}
]
}
命名路由嵌套
可为嵌套路由命名,便于编程式导航:
{
path: '/settings',
component: Settings,
children: [
{
path: 'account',
name: 'settings.account',
component: AccountSettings
}
]
}
路由守卫应用
嵌套路由支持全局守卫和局部守卫:
{
path: '/admin',
component: AdminLayout,
beforeEnter: (to, from, next) => {
// 父路由守卫逻辑
},
children: [
{
path: 'dashboard',
component: AdminDashboard,
beforeEnter: (to, from, next) => {
// 子路由专属守卫
}
}
]
}
注意事项
- 子路由路径不要以
/开头,否则会被解析为根路径 - 确保每个嵌套层级都有对应的
<router-view>出口 - 复杂项目建议使用路由模块化拆分
- 可通过
props: true将路由参数作为props传递
通过合理设计嵌套路由,可以构建清晰的路由层级,实现复杂应用的路由管理。






