如何用router-view实现嵌套路由,完整使用示例
在 Vue.js 中使用 <router-view> 实现 嵌套路由 的核心思路是:通过 children 属性定义子路由,并在父组件中使用 <router-view> 作为子路由的挂载点。以下是完整的使用示例及详细解释:
✅ 核心概念
- 父路由:顶层路由(如
/user) - 子路由:隶属于父路由的二级路由(如
/user/profile,/user/settings) <router-view>:动态渲染匹配当前 URL 的组件- 路径拼接规则:子路由的
path是相对于父路由的路径追加的
📁 项目结构示例
src/
├── router/ # 路由配置文件
│ └── index.js # 主路由文件
├── views/ # 视图组件目录
│ ├── UserLayout.vue # 父级布局组件 (含 <router-view>)
│ │ ├── components/ # 子组件存放位置
│ │ │ ├── Profile.vue
│ │ │ └── Settings.vue
│ └── Home.vue # 其他独立页面
└── App.vue # 根组件
🔧 Step 1: 配置路由 (router/index.js)
import { createRouter, createWebHistory } from 'vue-router';
// 引入组件
import Home from '../views/Home.vue';
import UserLayout from '../views/UserLayout.vue';
import Profile from '../views/UserLayout/components/Profile.vue';
import Settings from '../views/UserLayout/components/Settings.vue';const routes = [{path: '/',name: 'Home',component: Home},{path: '/user', // 父路由路径component: UserLayout, // 父级布局组件children: [ // 子路由列表{path: 'profile', // 完整路径变为 /user/profilename: 'UserProfile',component: Profile},{path: 'settings', // 完整路径变为 /user/settingsname: 'UserSettings',component: Settings}]}
];const router = createRouter({history: createWebHistory(),routes
});export default router;
🎨 Step 2: 创建父级布局组件 (views/UserLayout.vue)
此组件负责整体布局,内部包含一个 <router-view> 用于显示子路由内容。
<template><div class="user-container"><!-- 导航菜单 --><nav><router-link to="/user/profile">个人资料</router-link> |<router-link to="/user/settings">账户设置</router-link></nav><!-- 子路由出口 --><router-view></router-view> <!-- 就是这里! --></div>
</template><script>
export default {name: 'UserLayout'
};
</script>
📝 Step 3: 创建子组件 (views/UserLayout/components/*.vue)
Profile.vue 示例:
<template><div><h2>个人资料页</h2><p>这里是用户的详细信息...</p></div>
</template>
Settings.vue 示例:
<template><div><h2>账户设置</h2><p>修改密码、通知偏好等...</p></div>
</template>
🖥️ Step 4: 根组件 App.vue
只需一个简单的 <router-view>:
<template><div id="app"><router-view></router-view> <!-- 整个应用的入口 --></div>
</template>
🚀 运行效果说明
| URL | 显示内容 | 备注 |
|---|---|---|
/ | Home 组件 | 默认首页 |
/user/profile | UserLayout + Profile 组件 | 父布局 + 子组件 |
/user/settings | UserLayout + Settings 组件 | 父布局 + 另一个子组件 |
⚠️ 常见问题解决
Q1: 为什么子路由没生效?
- 确保父路由的
component指向的组件中确实有<router-view> - 检查子路由的
path是否与父路由形成正确层级(不要加多余的/)
Q2: 如何访问子路由?
- 方式一:直接输入 URL(如
/user/profile) - 方式二:使用
<router-link>生成链接(已在示例中实现)
Q3: 如何在子路由中获取参数?
若需动态参数,可改为:
children: [{ path: 'detail/:id', component: UserDetail }
]
然后在组件中通过 this.$route.params.id 获取
📚 进阶技巧
- 重定向:可在父路由添加
redirect: 'profile'使/user自动跳转到/user/profile - 懒加载:使用动态导入优化性能:
const Profile = () => import('../views/UserLayout/components/Profile.vue'); - 嵌套多层:支持无限层级嵌套,只需继续添加
children属性
📌 总结
| 要素 | 作用 | 示例值 |
|---|---|---|
path | 路由匹配路径 | 'user', 'profile' |
component | 匹配成功时加载的组件 | UserLayout |
children | 定义子路由 | [{ path: 'profile', ...}] |
<router-view> | 子路由的渲染容器 | 放在父组件模板中 |
<router-link> | 生成路由链接 | <router-link to="/user/profile"> |
通过这种方式,你可以构建出清晰的多级路由结构,适用于后台管理系统、电商详情页等复杂场景。
