vue实现路由的嵌套
路由嵌套的实现
在Vue Router中,嵌套路由允许在父路由组件内渲染子路由组件,适用于多层级页面结构(如后台管理系统)。以下是具体实现方法:
定义嵌套路由配置
在路由配置文件中,通过children属性定义嵌套关系:
const routes = [
{
path: '/parent',
component: ParentComponent,
children: [
{
path: 'child',
component: ChildComponent
},
{
path: 'another-child',
component: AnotherChildComponent
}
]
}
]
- 父路由路径为
/parent - 子路由路径会自动拼接为
/parent/child(无需写完整路径) - 子路由的组件将渲染在父组件的
<router-view>占位符处
父组件模板设置
父组件模板中必须包含<router-view>作为子路由的出口:
<!-- ParentComponent.vue -->
<div>
<h2>父组件</h2>
<router-view></router-view> <!-- 子组件将在此渲染 -->
</div>
子组件开发
子组件开发与普通组件无异:
<!-- ChildComponent.vue -->
<div>
<h3>子组件内容</h3>
</div>
动态路由嵌套
支持在嵌套路由中使用动态参数:
{
path: '/user/:id',
component: User,
children: [
{
path: 'profile',
component: UserProfile
},
{
path: 'posts',
component: UserPosts
}
]
}
访问路径示例:
/user/123/profile/user/456/posts
默认子路由
设置path: ''可指定默认渲染的子路由:
{
path: '/dashboard',
component: Dashboard,
children: [
{
path: '',
component: DashboardDefault
},
{
path: 'analytics',
component: DashboardAnalytics
}
]
}
访问/dashboard时会自动渲染DashboardDefault组件
命名视图嵌套
复杂布局可使用命名视图实现多路由出口:
{
path: '/admin',
components: {
default: AdminLayout,
sidebar: AdminSidebar
},
children: [
{
path: 'users',
components: {
default: UserList,
sidebar: UserMenu
}
}
]
}
对应模板需匹配name属性:
<router-view name="sidebar"></router-view>
<router-view></router-view> <!-- 默认 default -->
路由跳转方式
嵌套路由的跳转与普通路由相同:
<router-link to="/parent/child">跳转</router-link>
或编程式导航:
this.$router.push('/parent/another-child')
注意事项
- 嵌套路由的路径是相对路径,不要以
/开头 - 确保每个父级模板都有
<router-view>出口 - 可通过
$route.matched访问当前匹配的所有路由记录 - 嵌套过深时考虑使用路由模块化拆分







