vue实现路由的嵌套
Vue 实现路由嵌套的方法
在 Vue 中,路由嵌套可以通过 Vue Router 的 children 配置项实现。嵌套路由允许在父路由组件中渲染子路由组件,适合构建多层级的页面结构。
安装 Vue Router
确保项目中已安装 Vue Router。如果未安装,可以通过以下命令安装:
npm install vue-router
配置嵌套路由
在路由配置文件(通常是 router/index.js)中,通过 children 定义嵌套路由:

import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{
path: '/parent',
component: () => import('@/views/Parent.vue'),
children: [
{
path: 'child',
component: () => import('@/views/Child.vue'),
},
{
path: 'another-child',
component: () => import('@/views/AnotherChild.vue'),
},
],
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
父组件中放置 <router-view>
在父路由组件(如 Parent.vue)中,需要通过 <router-view> 标签预留子路由的渲染位置:
<template>
<div>
<h1>Parent Component</h1>
<router-view></router-view>
</div>
</template>
访问嵌套路由
访问嵌套路由时,路径需包含父路由和子路由的路径。例如:

/parent/child渲染Parent.vue和Child.vue/parent/another-child渲染Parent.vue和AnotherChild.vue
默认子路由
可以通过 redirect 或空路径设置默认子路由:
children: [
{
path: '',
component: () => import('@/views/DefaultChild.vue'),
},
// 其他子路由
],
动态路由嵌套
嵌套路由也支持动态路径参数:
{
path: '/user/:id',
component: () => import('@/views/User.vue'),
children: [
{
path: 'profile',
component: () => import('@/views/UserProfile.vue'),
},
],
}
通过以上步骤,可以灵活实现 Vue 中的路由嵌套功能。






