1893 字
9 分钟
Vue 3 路由实例分析笔记
Vue 3 路由实例分析笔记
一、文件基本信息
文件路径:项目名/src/router/index.ts
技术栈:Vue 3 + Vue Router 4 + TypeScript
核心功能:定义应用路由结构,管理页面导航与权限控制
二、Vue Router 4 静态路由语法详解
1. 路由配置基础结构
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
// 静态路由数组export const constantRoutes: RouteRecordRaw[] = [ { // 路由路径 path: '/', // 路由组件 component: Layout, // 路由元信息 meta: { title: '首页', icon: 'icon-home' }, // 子路由 children: [ // 子路由配置 ] }];2. 核心配置项详解
| 配置项 | 类型 | 必选 | 说明 | 示例值 |
|---|---|---|---|---|
path | string | ✅ | 路由路径,支持动态路由和通配符 | /dashboard, :id/, * |
component | Component | () => Promise | ✅ | 路由对应的组件,支持懒加载 | Layout, () => import('@/views/xxx.vue') |
name | string | ❌ | 路由名称,用于命名路由跳转 | Dashboard |
meta | Record<string, any> | ❌ | 路由元信息,自定义字段 | { title: '首页', icon: 'icon-home' } |
redirect | string | RouteLocationRaw | ❌ | 重定向路径 | /dashboard, { name: 'Dashboard' } |
children | RouteRecordRaw[] | ❌ | 子路由数组,实现嵌套路由 | [{ path: 'xxx', component: XXX }] |
alias | string | string[] | ❌ | 路由别名,可通过多个路径访问同一组件 | ['/home', '/index'] |
props | boolean | object | Function | ❌ | 是否将路由参数作为组件 props 传递 | true, { static: 'value' } |
beforeEnter | NavigationGuardWithThis | ❌ | 路由独享守卫 | (to, from, next) => next() |
3. 组件懒加载语法
基础懒加载
component: () => import('@/views/dashboard/index.vue')带命名的懒加载
component: () => import(/* webpackChunkName: "dashboard" */ '@/views/dashboard/index.vue')动态导入懒加载
const Dashboard = () => import('@/views/dashboard/index.vue');component: Dashboard4. 路由匹配规则
| 路径模式 | 匹配路径 | 匹配参数 |
|---|---|---|
/user | /user | 无 |
/user/:id | /user/123 | { id: '123' } |
/user/:id/posts | /user/123/posts | { id: '123' } |
/user/* | /user/123/posts/456 | 无 |
/user/:id/:name? | /user/123 或 /user/123/john | { id: '123', name: undefined } 或 { id: '123', name: 'john' } |
5. 路由元信息(meta)最佳实践
meta: { title: '页面标题', // 用于面包屑、标签页、浏览器标题 icon: 'icon-home', // 用于侧边栏图标 affix: true, // 是否固定在标签页 showSidebar: true, // 是否在侧边栏显示 breadcrumb: true, // 是否显示面包屑 requiresAuth: true, // 是否需要登录权限 roles: ['admin', 'editor'], // 允许访问的角色 keepAlive: true // 是否缓存组件}6. 嵌套路由语法
{ path: '/parent', component: ParentComponent, children: [ { // 匹配 /parent/child path: 'child', component: ChildComponent }, { // 匹配 /parent/child/:id path: 'child/:id', component: ChildDetailComponent } ]}三、路由模块设计模式
1. 基础路由模式
├── 登录页 (/login)├── 404页 (/404)├── 重定向页 (/redirect/:path(.*))└── 首页 (/) └── 仪表盘 (/dashboard)2. 业务模块路由模式
├── 业务模块1 (/module1)│ ├── 列表页 (/module1/list)│ └── 详情页 (/module1/:id)│ ├── 基础信息 (/module1/:id/base)│ └── 高级设置 (/module1/:id/advanced)└── 业务模块2 (/module2) └── 功能页 (/module2/function)3. 系统设置路由模式
├── 系统设置 (/system)│ ├── 内容管理 (/system/content)│ │ ├── 文章管理 (/system/content/articles)│ │ └── 分类管理 (/system/content/categories)│ ├── 用户管理 (/system/user)│ └── 权限管理 (/system/permission)四、路由创建与配置
1. 创建路由实例
// 创建路由实例const router = createRouter({ // 路由模式:hash 或 history // hash模式:createWebHashHistory() // history模式:createWebHistory(import.meta.env.BASE_URL) history: createWebHistory(import.meta.env.BASE_URL), // 路由数组 routes: constantRoutes as RouteRecordRaw[], // 滚动行为配置 scrollBehavior: () => ({ left: 0, top: 0 })});2. 路由模式对比
| 模式 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| hash | 无需后端配置,兼容性好 | URL 包含 #,不美观 | 静态网站,小型应用 |
| history | URL 美观,符合 RESTful 风格 | 需要后端配置,兼容性稍差 | 大型应用,需要 SEO |
3. 滚动行为配置
scrollBehavior: (to, from, savedPosition) => { // 如果是返回,保持原滚动位置 if (savedPosition) { return savedPosition; } else { // 否则滚动到顶部 return { left: 0, top: 0 }; }}五、路由守卫与权限控制
1. 全局前置守卫
router.beforeEach((to, from, next) => { // 权限检查逻辑 if (to.meta.requiresAuth && !isLoggedIn()) { next('/login'); } else { next(); }});2. 路由重置功能
export function resetRouter() { // 重置路由逻辑 permissionStore.routes.forEach(route => { const name = route.name; if (name && router.hasRoute(name)) { router.removeRoute(name); } });}六、路由使用最佳实践
1. 路由命名规范
- 使用 PascalCase 命名路由名称
- 路由名称应与组件名称保持一致
- 包含模块前缀,如
UserList、UserDetail
2. 组件路径规范
- 使用绝对路径,配合
@别名 - 按模块组织视图组件
- 保持组件文件名与功能一致
3. 路由元信息规范
- 统一元信息字段命名
- 避免过度使用元信息
- 元信息应仅包含与路由相关的数据
4. 路由拆分策略
// 基础路由拆分src/router/├── index.ts // 路由主文件├── constantRoutes.ts // 静态路由配置├── asyncRoutes.ts // 动态路由配置└── modules/ // 模块化路由 ├── user.ts // 用户模块路由 └── system.ts // 系统模块路由七、路由可视化结构图
┌─────────────────────────────────────────────────────────────────┐│ Vue 3 Router 结构 │├─────────┬──────────────┬──────────────┬──────────────┬─────────┤│ 基础路由│ 业务模块1 │ 业务模块2 │ 统计分析 │ 系统设置 ││ /login │ /module1/ │ /module2/ │ /statistics/ │ /system/ ││ /404 └──────────────┴──────────────┴──────────────┴─────────┤│ /redirect │└─────────────────────────────────────────────────────────────────┘八、静态路由与动态路由结合
1. 静态路由定义
// 静态路由:不需要权限即可访问的路由export const constantRoutes: RouteRecordRaw[] = [ { path: '/login', component: Login }, { path: '/404', component: NotFound }, { path: '/', component: Layout, redirect: '/dashboard' }];2. 动态路由定义
// 动态路由:需要权限才能访问的路由export const asyncRoutes: RouteRecordRaw[] = [ { path: '/admin', component: Layout, meta: { roles: ['admin'] // 只有 admin 角色可以访问 }, children: [ // 管理员功能路由 ] }];3. 路由合并策略
// 初始只加载静态路由const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: constantRoutes});
// 登录后根据权限动态添加路由export function addRoutes(routes: RouteRecordRaw[]) { routes.forEach(route => { router.addRoute(route); });}九、路由性能优化
1. 组件懒加载
// 推荐:使用动态导入实现懒加载component: () => import('@/views/dashboard/index.vue')
// 不推荐:直接导入组件import Dashboard from '@/views/dashboard/index.vue';component: Dashboard2. 路由组件缓存
<!-- 在 App.vue 中使用 keep-alive 缓存路由组件 --><template> <router-view v-slot="{ Component }"> <keep-alive> <component :is="Component" v-if="$route.meta.keepAlive" /> </keep-alive> <component :is="Component" v-else /> </router-view></template>3. 路由分割
// 按模块分割路由const UserRoutes = () => import('./modules/user');const SystemRoutes = () => import('./modules/system');
// 路由注册router.addRoute(UserRoutes);router.addRoute(SystemRoutes);十、路由调试与测试
1. 路由调试技巧
// 打印路由信息router.beforeEach((to, from) => { console.log('从', from.path, '跳转到', to.path); console.log('路由元信息:', to.meta);});2. 路由测试方法
// 使用 Vue Test Utils 测试路由import { mount } from '@vue/test-utils';import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({ history: createWebHistory(), routes: constantRoutes});
const wrapper = mount(App, { global: { plugins: [router] }});十一、路由设计原则
1. 清晰的层级结构
- 保持路由层级不超过 4 层
- 模块间路由相互独立
- 遵循 RESTful 设计风格
2. 良好的可扩展性
- 支持动态添加路由
- 支持路由模块化拆分
- 便于添加新的业务模块
3. 安全性考虑
- 路由权限控制
- 防止未授权访问
- 敏感路由加密
4. 用户体验优先
- 合理的重定向策略
- 平滑的页面过渡
- 清晰的面包屑导航
十二、总结
Vue Router 4 的静态路由是构建 Vue 3 应用的基础,掌握其语法和设计模式对于开发高效、可维护的单页应用至关重要。本笔记从静态路由语法详解、路由模块设计、路由创建配置、性能优化等多个角度进行了全面介绍,适合不同层次的前端开发者学习和参考。
通过合理设计路由结构、使用懒加载、配置丰富的元信息,可以构建出既高效又易于维护的路由系统。在实际项目中,应根据业务需求选择合适的路由模式和设计方案,同时注重路由的安全性和用户体验。
部分信息可能已经过时




