如何实现vue路由嵌套
实现 Vue 路由嵌套
在 Vue Router 中,路由嵌套是通过 children 配置项实现的。嵌套路由允许在父路由组件中渲染子路由组件,适用于多层级页面结构。
基本配置方法
- 定义路由配置
在路由配置文件中,通过
children属性定义嵌套路由。父路由需设置component,子路由路径可以是相对路径或绝对路径。
const routes = [
{
path: '/parent',
component: ParentComponent,
children: [
{
path: 'child', // 相对路径,实际路径为 /parent/child
component: ChildComponent
},
{
path: '/parent/another-child', // 绝对路径
component: AnotherChildComponent
}
]
}
]
- 父组件中放置
<router-view>父路由组件模板中需预留<router-view>作为子路由的出口。
<!-- ParentComponent.vue -->
<template>
<div>
<h2>父组件</h2>
<router-view></router-view>
</div>
</template>
动态路由嵌套
嵌套路由支持动态路径参数,参数会传递给子组件。
const routes = [
{
path: '/user/:id',
component: User,
children: [
{
path: 'profile',
component: UserProfile
}
]
}
]
默认子路由
通过空路径设置默认子路由,当访问父路由时自动渲染该子路由。
const routes = [
{
path: '/dashboard',
component: Dashboard,
children: [
{
path: '', // 默认子路由
component: DashboardDefault
},
{
path: 'stats',
component: DashboardStats
}
]
}
]
命名视图嵌套
对于命名视图,需在子路由中同样指定 components 选项。
const routes = [
{
path: '/layout',
components: {
default: Layout,
sidebar: Sidebar
},
children: [
{
path: 'content',
components: {
default: Content,
sidebar: ContentSidebar
}
}
]
}
]
路由跳转
在模板或代码中导航到嵌套路由时,路径需包含完整层级。
<router-link to="/parent/child">跳转子路由</router-link>
router.push('/parent/child')
注意事项
- 嵌套路由的路径匹配是累积的,父路由路径会作为前缀
- 子路由组件会继承父路由的
$route对象 - 确保每个嵌套层级都有对应的
<router-view>出口 - 对于复杂嵌套,考虑使用路由模块化拆分配置







