在构建中大型单页应用(SPA)时,页面结构往往比较复杂,比如仪表盘、用户中心、商品管理等模块通常包含多个子功能页面。为了更好地组织这些页面,Vue Router 提供了嵌套(多级)路由的功能。
通过嵌套路由,我们可以在父级组件中嵌入一个
来展示子级组件,实现类似“布局 + 内容”的结构。
本文将带你深入了解:
通过这篇文章,你将能够熟练地使用 Vue Router 构建具有层级结构的页面系统。
嵌套路由(Nested Routes) 是指在一个路由下挂载多个子路由,形成父子结构。常用于构建带有布局结构的页面,如侧边栏 + 主体内容。
/dashboard
├─ /dashboard/profile → 用户资料页
└─ /dashboard/settings → 设置页
特点:
在父组件内部展示;src/router/index.js
)import { createRouter, createWebHistory } from 'vue-router'
import DashboardLayout from '../views/DashboardLayout.vue'
import Profile from '../views/Profile.vue'
import Settings from '../views/Settings.vue'
const routes = [
{
path: '/dashboard',
name: 'Dashboard',
component: DashboardLayout,
children: [
{
path: 'profile', // 注意这里没有斜杠 `/profile`,表示是 `/dashboard/profile`
component: Profile
},
{
path: 'settings',
component: Settings
}
]
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
小贴士:
/
开头;redirect
:{
path: '/dashboard',
name: 'Dashboard',
component: DashboardLayout,
redirect: '/dashboard/profile',
children: [...]
}
DashboardLayout.vue
)
仪表盘
效果说明:
会动态渲染对应的子组件;场景 | 描述 |
---|---|
后台管理系统 | 多个菜单项共享左侧导航栏或顶部菜单 |
用户中心 | 包含订单、地址、账户信息等多个子页面 |
商品管理 | 包括商品列表、新增商品、编辑商品等页面 |
表单向导 | 分步骤完成表单填写,每一步为一个子路由 |
动态权限控制 | 根据用户角色动态加载不同子路由 |
如果你想让某个子路由作为默认展示页面,可以使用 redirect
:
{
path: '/dashboard',
name: 'Dashboard',
component: DashboardLayout,
redirect: '/dashboard/profile',
children: [
{
path: 'profile',
component: Profile
},
...
]
}
Vue Router 支持无限层级的嵌套:
{
path: '/user',
component: UserLayout,
children: [
{
path: ':id',
component: UserProfile,
children: [
{
path: 'edit',
component: EditProfile
}
]
}
]
}
访问路径:
/user/123/edit
→ 显示 EditProfile
组件params
)在嵌套结构中,子组件可以通过 $route.params
获取所有层级的参数:
// 路由配置:
// path: '/user/:id/profile'
export default {
mounted() {
console.log(this.$route.params.id) // 输出用户 ID
}
}
你可以结合命名视图实现更复杂的布局组合:
{
path: '/layout',
component: MainLayout,
children: [
{
path: 'content',
components: {
default: ContentMain,
sidebar: SideBar
}
}
]
}
模板中使用:
问题 | 解决方案 |
---|---|
子路由不显示 | 检查是否遗漏了
|
子路由路径错误 | 路径不要加 / ,应为相对路径 |
页面空白无内容 | 检查组件路径是否正确、是否未匹配任何组件 |
无法获取 $route |
确保组件已注册并处于 中 |
页面不刷新但数据没变 | 使用 key 强制重新渲染组件 |
功能 | 推荐方式 |
---|---|
父子路由结构 | 使用 children 配置 |
默认子路由展示 | 使用 redirect |
获取路由参数 | this.$route.params.xxx |
多层嵌套支持 | ✅ 官方支持 |
多视图配合 | 使用命名
|
推荐程度 | ✅✅ 强烈推荐掌握 |
感谢您的阅读!如果你有任何疑问或想要分享的经验,请在评论区留言交流!