Mobile wallpaper 1Mobile wallpaper 2Mobile wallpaper 3Mobile wallpaper 4Mobile wallpaper 5Mobile wallpaper 6
804 字
4 分钟
嵌套路由注意事项总结

嵌套路由注意事项总结#

根据在 meeting-book-system 项目中实现嵌套路由的经验,总结以下关键注意事项,帮助开发者避免常见陷阱。

1. 路由层级设计要合理#

建议层级结构#

  • 第一层:整体布局框架(如左侧菜单、顶部导航)
  • 第二层:模块专属布局(如二级菜单)
  • 第三层:具体功能页面

示例#

/statistics # 第一层:整体布局
└─ StatisticsMenu # 第二层:统计模块二级菜单
├─ total # 第三层:总览功能
└─ action # 第三层:活动统计

2. 父路由必须包含 <router-view />#

这是嵌套路由的核心规则!父路由组件必须包含 <router-view /> 才能渲染子路由组件。

错误示例#

<!-- 父路由组件 -->
<template>
<div>这是父组件</div>
<!-- 缺少 <router-view />,子路由无法渲染 -->
</template>

正确示例#

<!-- 父路由组件 -->
<template>
<div>
这是父组件
<router-view /><!-- 子路由将在这里渲染 -->
</div>
</template>

3. 二级菜单与路由的正确关联#

动态生成菜单时,确保从路由配置中获取正确的路由数据。

示例代码#

// 正确获取二级菜单数据
const list = router.getRoutes().filter(route => route.name === 'StatisticsMenu');
if (list.length > 0) {
menuList.value = list[0].children || [];
}

4. 合理配置重定向(redirect)#

访问父路由时,通过 redirect 自动跳转到默认子路由,避免空白页面。

示例配置#

const routes = [
{
path: '/statistics/total',
name: 'total',
component: LayoutComponent,
redirect: '/statistics/total/byCollege', // 自动跳转到默认子路由
children: [
{ path: 'byCollege', name: 'byCollege', component: ByCollegeComponent },
{ path: 'bySpace', name: 'bySpace', component: BySpaceComponent }
]
}
];

5. 组件职责要清晰#

  • 父组件:负责布局和子路由容器
  • 子组件:负责具体业务逻辑和页面内容

示例#

  • index.vue:只包含 <router-view />,作为路由容器
  • bySpace.vue:包含完整的业务逻辑和UI组件

6. 注意路由匹配顺序#

Vue Router 按照路由定义的顺序匹配,更具体的路由应该放在前面

错误示例#

const routes = [
{ path: '/user/:id', component: UserComponent }, // 通用路由放在前面
{ path: '/user/profile', component: ProfileComponent } // 具体路由放在后面
];

正确示例#

const routes = [
{ path: '/user/profile', component: ProfileComponent }, // 具体路由放在前面
{ path: '/user/:id', component: UserComponent } // 通用路由放在后面
];

7. 调试技巧#

  1. 检查路由变化:使用浏览器开发者工具查看路由变化
  2. 查看 $route 对象:确认当前路由信息是否正确
  3. 检查组件路径:确保路由配置中 component 路径正确
  4. 检查菜单数据:确认菜单组件获取的路由数据是否正确

8. 避免组件命名冲突#

不同模块的组件尽量使用唯一命名,避免混淆。

示例#

  • statistics/layout.vue:统计模块布局组件
  • statistics/index.vue:统计模块入口组件(路由容器)

总结#

嵌套路由的核心是父子组件的正确配合,父组件提供容器,子组件负责内容。遵循以上注意事项,可以有效避免嵌套路由中常见的组件不显示、菜单异常、路由匹配错误等问题。

记住这个黄金法则:父路由有 <router-view />,子路由才能被渲染!

嵌套路由注意事项总结
https://yukilain.com/posts/嵌套路由注意事项/
作者
Yukilain
发布于
2025-12-02
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

封面
示例歌曲
示例艺术家
封面
示例歌曲
示例艺术家
0:00 / 0:00