Vue嵌套路由
下面,我们来系统的梳理关于 Vue Router 嵌套路由 的基本知识点:
一、嵌套路由的核心概念
1.1 什么是嵌套路由?
嵌套路由是Vue Router的核心功能之一,允许在路由内部定义子路由,形成路由层次结构。这种机制使开发者能够创建复杂的用户界面,其中多个组件层级嵌套在一起。
1.2 为什么需要嵌套路由?
- 构建具有多层布局的应用(如后台管理系统)
- 在父组件中保持公共UI(如导航栏)的同时切换子内容
- 实现组件级别的代码组织和复用
- 创建更符合用户认知的URL结构
1.3 嵌套路由的工作原理
http://example.com/parent/child/grandchild│ │ │ ││ │ │ └── 孙子路由组件│ │ └── 子路由组件│ └── 父路由组件└── 根组件
二、嵌套路由配置详解
2.1 基本配置语法
使用children
属性定义嵌套路由:
const routes = [{path: '/parent',component: ParentComponent,children: [{// 当 /parent 匹配时// ChildComponent 会被渲染在 ParentComponent 的 <router-view> 中path: '', // 默认子路由component: ChildComponent},{// 当 /parent/child-a 匹配时path: 'child-a', // 注意:不要以斜杠开头component: ChildAComponent},{// 当 /parent/child-b 匹配时path: 'child-b',component: ChildBComponent}]}
]
2.2 多层嵌套配置
嵌套路由可以无限层级:
const routes = [{path: '/dashboard',component: DashboardLayout,children: [{path: '',component: DashboardHome},{path: 'user',component: UserContainer,children: [{path: '',component: UserList},{path: ':id',component: UserDetail,children: [{path: 'profile',component: UserProfile},{path: 'settings',component: UserSettings}]}]}]}
]
2.3 重要配置选项
选项 | 说明 | 示例 |
---|---|---|
path | 子路由路径(不以/ 开头) | 'child' |
component | 要渲染的组件 | ChildComponent |
name | 命名路由(推荐) | 'parent.child' |
redirect | 重定向到子路由 | redirect: 'child-default' |
meta | 路由元信息 | meta: { requiresAuth: true } |