Vue3 路由使用说明文档
1. 概述
本文档基于Trae Vue项目实际配置,系统梳理Vue3中Vue Router的使用要点,涵盖基础配置、编程式导航、路由守卫、动态路由等核心功能模块。
2. 项目路由架构
2.1 路由配置核心文件
项目路由配置位于 src/router/index.js,采用Vue Router 4.x标准配置模式:
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/login',
name: 'Login',
component: () => import('../views/LoginView.vue')
},
{
path: '/',
name: 'Home',
component: () => import('../views/HomeView.vue'),
meta: { requiresAuth: true }
}
// ... 其他路由配置
]
})
2.2 路由配置要素
| 配置项 | 类型 | 说明 | 项目示例 |
|---|---|---|---|
| history | Function | 路由历史模式 | createWebHistory() |
| routes | Array | 路由定义数组 | 10个主要路由项 |
| path | String | 路由路径 | /login, /about |
| name | String | 路由名称标识 | Home, Login |
| component | Function | 异步组件加载 | () => import() |
| meta | Object | 路由元信息 | { requiresAuth: true } |
3. 路由守卫实现
3.1 全局前置守卫
项目采用标准的路由守卫模式实现权限控制:
router.beforeEach((to, from, next) => {
// 页面标题设置
if (to.meta?.title) {
document.title = `${to.meta.title} - Trae Vue`
}
// 权限验证逻辑
const token = localStorage.getItem('token')
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
if (requiresAuth && !token) {
next('/login')
} else {
next()
}
})
3.2 守卫参数说明
| 参数 | 类型 | 作用 |
|---|---|---|
| to | Route | 目标路由对象 |
| from | Route | 来源路由对象 |
| next | Function | 导航控制函数 |
3.3 导航控制方法
| 调用方式 | 行为描述 |
|---|---|
next() | 继续当前导航 |
next('/login') | 重定向到指定路由 |
next(false) | 中断当前导航 |
4. 组件路由集成
4.1 组合式API使用
项目采用Vue3组合式API模式进行路由操作:
import { useRouter, useRoute } from 'vue-router'
export default {
setup() {
const router = useRouter() // 路由实例
const route = useRoute() // 当前路由信息
// 路由监听
watch(() => route.path, (newPath) => {
console.log('路由变化:', newPath)
})
return { router, route }
}
}
4.2 核心API对照
| API | 返回类型 | 主要用途 |
|---|---|---|
useRouter() | Router | 编程式导航、全局配置 |
useRoute() | Route | 获取当前路由状态 |
5. 导航菜单实现
5.1 声明式导航
侧边栏菜单组件采用声明式导航模式:
<template>
<a-menu v-model:selectedKeys="selectedKeys" mode="inline">
<a-menu-item key="home">
<router-link to="/">
<HomeOutlined />
<span>首页</span>
</router-link>
</a-menu-item>
</a-menu>
</template>
<script setup>
import { useRoute } from 'vue-router'
import { watch, ref } from 'vue'
const route = useRoute()
const selectedKeys = ref(['home'])
// 路由状态同步
watch(() => route.path, (newPath) => {
const key = newPath.substring(1) || 'home'
selectedKeys.value = [key]
})
</script>
6. 动态路由与参数处理
6.1 参数传递机制
| 参数类型 | URL格式 | 获取方式 | 示例 |
|---|---|---|---|
| 路径参数 | /user/:id | route.params.id | /user/123 |
| 查询参数 | /search?q=vue | route.query.q | ?q=vue&page=1 |
6.2 编程式导航实现
// 基础路径跳转
const toAbout = () => router.push('/about')
// 命名路由跳转
const toUserProfile = (userId) => {
router.push({
name: 'UserProfile',
params: { id: userId }
})
}
// 查询参数传递
const toSearch = (keyword) => {
router.push({
path: '/search',
query: { q: keyword, page: 1 }
})
}
// 替换模式(无历史记录)
const replaceToHome = () => router.replace('/home')
7. 路由元信息应用
7.1 Meta字段配置
项目路由元信息配置示例:
{
path: '/admin',
name: 'Admin',
component: () => import('../views/AdminView.vue'),
meta: {
requiresAuth: true, // 权限要求
title: '管理后台', // 页面标题
roles: ['admin'], // 角色要求
keepAlive: true // 缓存标识
}
}
7.2 元信息应用场景
| Meta字段 | 数据类型 | 应用场景 |
|---|---|---|
requiresAuth | Boolean | 登录权限验证 |
title | String | 页面标题设置 |
roles | Array | 角色权限控制 |
keepAlive | Boolean | 组件缓存控制 |
8. 路由性能优化
8.1 懒加载实现
项目全面采用异步组件加载模式:
const routes = [
{
path: '/heavy-page',
component: () => import(
/* webpackChunkName: "heavy-page" */
/* webpackPrefetch: true */
'../views/HeavyPage.vue'
)
}
]
8.2 代码分割策略
| 优化手段 | 实现方式 | 预期效果 |
|---|---|---|
| 异步加载 | () => import() | 减少初始包体积 |
| 预加载 | webpackPrefetch | 提升后续页面加载速度 |
| 命名分包 | webpackChunkName | 便于调试和分析 |
9. 高级路由特性
9.1 嵌套路由配置
const routes = [
{
path: '/dashboard',
component: () => import('../views/DashboardLayout.vue'),
children: [
{
path: '', // 默认子路由
name: 'DashboardHome',
component: () => import('../views/dashboard/Home.vue')
},
{
path: 'users',
name: 'DashboardUsers',
component: () => import('../views/dashboard/Users.vue')
}
]
}
]
9.2 命名视图实现
// 路由配置
const routes = [
{
path: '/layout',
components: {
default: () => import('../views/MainContent.vue'),
sidebar: () => import('../views/Sidebar.vue'),
header: () => import('../views/Header.vue')
}
}
]
// 模板使用
<template>
<div class="layout-container">
<router-view name="header" />
<router-view name="sidebar" />
<router-view />
</div>
</template>
9.3 动态路由管理
// 运行时路由添加
router.addRoute({
path: '/admin',
name: 'Admin',
component: () => import('../views/Admin.vue'),
meta: { requiresAuth: true, roles: ['admin'] }
})
// 嵌套路由动态添加
router.addRoute('Dashboard', {
path: 'reports',
component: () => import('../views/dashboard/Reports.vue')
})
9.4 路由守卫进阶
// 全局后置钩子
router.afterEach((to, from) => {
// 页面访问统计
analytics.trackPageView(to.path)
// 滚动位置重置
window.scrollTo(0, 0)
})
// 路由独享守卫
const routes = [
{
path: '/admin',
beforeEnter: (to, from, next) => {
const userRole = getUserRole()
userRole === 'admin' ? next() : next('/unauthorized')
}
}
]
// 组件内守卫
export default {
beforeRouteEnter(to, from, next) {
// 组件实例创建前调用
next(vm => vm.fetchData())
},
beforeRouteUpdate(to, from, next) {
// 路由更新但组件复用时调用
this.fetchData(to.params.id)
next()
},
beforeRouteLeave(to, from, next) {
// 离开当前路由时调用
this.hasUnsavedChanges ?
confirm('有未保存的更改,确定要离开吗?') ? next() : next(false) :
next()
}
}
9.5 路由正则匹配
const routes = [
{
// 数字ID匹配
path: '/user/:id(\\d+)',
component: () => import('../views/UserDetail.vue')
},
{
// 404页面处理
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('../views/NotFound.vue')
},
{
// 可选参数
path: '/user/:id?',
component: () => import('../views/User.vue')
},
{
// 重复参数匹配
path: '/files/:path+',
component: () => import('../views/FileBrowser.vue')
}
]
9.6 路由过渡效果
<template>
<router-view v-slot="{ Component, route }">
<transition
:name="route.meta.transition || 'fade'"
mode="out-in"
:duration="{ enter: 300, leave: 200 }"
>
<component :is="Component" :key="route.fullPath" />
</transition>
</router-view>
</template>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
10. 路由错误处理
10.1 导航错误捕获
// 全局错误处理
router.onError((error) => {
if (error.name === 'NavigationDuplicated') {
console.warn('重复导航被阻止:', error.message)
} else {
console.error('路由导航错误:', error)
// 错误上报处理
reportError(error)
}
})
10.2 路由匹配失败
const routes = [
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('../views/NotFound.vue'),
meta: { title: '页面未找到' }
}
]
11. 最佳实践总结
11.1 配置规范
- 路由命名:采用帕斯卡命名法,保持语义清晰
- 路径设计:遵循RESTful原则,层级结构明确
- 组件加载:统一使用异步加载,配合Webpack优化
- 元信息配置:建立完整的meta字段规范
11.2 性能优化
- 代码分割:按业务模块进行路由级别的代码分割
- 预加载策略:对关键路径实施预加载
- 缓存控制:合理使用keep-alive和路由缓存
- 错误处理:完善的路由错误捕获机制
11.3 安全考虑
- 权限验证:路由守卫中实现完整的权限校验
- 数据验证:对路由参数进行有效性验证
- 错误处理:防止路由错误导致的应用崩溃
- 日志记录:记录关键路由操作便于审计
12. 结论
Vue Router作为Vue3官方路由解决方案,提供了完整的路由管理功能。Trae Vue项目通过合理的路由配置、完善的权限控制、优化的加载策略,构建了健壮的单页面应用路由体系。
项目当前已实现核心路由功能,建议根据业务发展需要,逐步引入嵌套路由、命名视图等高级特性,持续优化用户体验和应用性能。
技术栈:Vue 3.0+ | Vue Router 4.0+ | Vite | JavaScript ES6+
2830

被折叠的 条评论
为什么被折叠?



