Vue Router 是 Vue.js 官方的路由管理器,它和 Vue.js 核心深度集成,让构建单页面应用(SPA)变得轻而易举。Vue Router 4 是专为 Vue 3 设计的版本,它在 API 设计、性能和类型支持上都有了显著的改进。
本文将从基础概念出发,深入探讨 Vue Router 4 的核心功能,包括基础路由定义、动态路径匹配、嵌套路由、导航守卫,并提供实战技巧和常见问题的排查指南。
1. Vue Router 4 基础入门
1.1 安装与初始化
首先,我们需要在 Vue 3 项目中安装 Vue Router 4。
npm install vue-router@4
或者使用 yarn:
yarn add vue-router@4
1.2 创建路由实例
在 Vue 3 中,我们通常在
src/router/index.js
(或
.ts
)文件中配置路由。
// src/router/index.js
import { createRouter, createWebHistory } from ‘vue-router’
// 1. 定义路由组件
// 也可以从其他文件导入
const Home = { template: ‘
‘ }
const About = { template: ‘
‘ }
// 2. 定义路由
// 每个路由应该映射一个组件
const routes = [
{ path: ‘/’, component: Home },
{ path: ‘/about’, component: About }
]
// 3. 创建路由实例
const router = createRouter({
// createWebHistory 使用 HTML5 模式 (去除 URL 中的 #)
// createWebHashHistory 使用 hash 模式
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
1.3 在 Vue 应用中挂载路由
在
main.js
中,我们需要将路由实例挂载到 Vue 应用上。
// src/main.js
import { createApp } from ‘vue’
import App from ‘./App.vue’
import router from ‘./router’ // 导入路由
const app = createApp(App)
app.use(router) // 使用路由插件
app.mount(‘#app’)
1.4 路由视图与导航
在组件模板中,我们使用
来显示匹配到的组件,使用
来进行导航。
2. 动态路径匹配 (Dynamic Route Matching)
很多时候,我们需要将某种模式映射到同一个组件,例如用户详情页,ID 不同但页面结构相同。
2.1 基本用法
使用冒号
:
来定义参数。
const routes = [
// 动态段名为 :id
{ path: ‘/user/:id’, component: User }
]
当访问
/user/123
时,
User
组件会被渲染。
2.2 在组件中获取参数
在 Vue 3 的组合式 API (Composition API) 中,我们使用
useRoute
钩子来获取路由参数。
用户 ID: {{ userId }}
2.3 响应式参数变化
默认情况下,当用户从
/user/1
导航到
/user/2
时,
相同的组件实例将被复用
。因为两个路由都渲染同一个
User
组件,组件的生命周期钩子不会被再次触发。
如果你需要在参数变化时做出响应(例如重新获取数据),你可以通过监听
route.params
来实现:
2.4 捕获所有路由或 404 Not Found
使用通配符
*
可以匹配任意路径,通常用于 404 页面。
const routes = [
// 将匹配所有以 /user- 开头的路径
{ path: ‘/user-*’, component: UserWildcard },
// 匹配所有未被前面路由匹配的路径
{ path: ‘/:pathMatch(.*)*’, component: NotFound }
]
注意
:
/:pathMatch(.*)*
捕获的参数是一个数组。例如,访问
/foo/bar
,
route.params.pathMatch
将是
[‘foo’, ‘bar’]
。如果你希望是字符串
‘foo/bar’
,可以使用
/:pathMatch(.*)
(去掉末尾的
*
)。
3. 嵌套路由 (Nested Routes)
实际的应用界面通常由多层嵌套的组件组成。例如,用户设置页面可能包含
Profile
、
Posts
和
Settings
等子页面。
3.1 配置嵌套路由
使用
children
数组来定义子路由。
const routes = [
{
path: ‘/user/:id’,
component: User,
children: [
// 当 /user/:id/profile 匹配时
// User 的
{ path: ‘profile’, component: UserProfile },
// 当 /user/:id/posts 匹配时
{ path: ‘posts’, component: UserPosts },
// 默认子路由
// 当路径仅为 /user/:id 时,重定向到 profile
{ path: ”, component: UserProfile }
]
}
]
3.2 嵌套路由的视图渲染
父组件
User.vue
中必须包含
来显示子组件。
用户中心
4. 导航守卫 (Navigation Guards)
导航守卫主要用来通过跳转或取消的方式守卫导航,常用于权限验证、页面标题修改、数据预加载等。
4.1 全局前置守卫 (Global Before Guards)
这是最常用的守卫,每次导航触发前都会调用。
// src/router/index.js
import { createRouter, createWebHistory } from ‘vue-router’
const router = createRouter({ … })
// 全局前置守卫
router.beforeEach((to, from, next) => {
// to: 即将要进入的目标 路由对象
// from: 当前导航正要离开的 路由对象
// next: 一定要调用该函数来 resolve 这个钩子
const isAuthenticated = localStorage.getItem(‘token’) // 假设这是登录状态
// 需要鉴权的路由元信息
if (to.meta.requiresAuth && !isAuthenticated) {
// 如果未登录,重定向到登录页
next({ path: ‘/login’, query: { redirect: to.fullPath } })
} else {
// 如果已登录或不需要鉴权,放行
next()
}
})
export default router
路由配置中添加元信息 (meta)
:
const routes = [
{
path: ‘/dashboard’,
component: Dashboard,
meta: { requiresAuth: true } // 标记该路由需要鉴权
},
{ path: ‘/login’, component: Login }
]
4.2 组件内的守卫
你可以直接在组件内定义守卫,这对于需要在组件销毁前取消某些操作很有用。
在 Vue 3 组合式 API 中,可以使用
onBeforeRouteUpdate
和
onBeforeRouteLeave
钩子:
5. 实战技巧
5.1 路由懒加载 (Lazy Loading)
对于大型应用,将所有路由对应的组件都打包进主包会导致体积过大。使用动态导入(
import()
)可以实现懒加载。
const routes = [
{
path: ‘/admin’,
// Webpack 会自动将其拆分为单独的 chunk
component: () => import(‘../views/AdminPanel.vue’)
},
{
path: ‘/about’,
// 带有命名的 chunk
component: () => import(/* webpackChunkName: “about” */ ‘../views/About.vue’)
}
]
5.2 路由过渡效果
结合 Vue 的
组件,可以给路由切换添加酷炫的过渡动画。
5.3 滚动行为 (Scroll Behavior)
利用
scrollBehavior
方法,可以在路由切换时控制页面滚动位置。
const router = createRouter({
history: createWebHistory(),
routes,
scrollBehavior(to, from, savedPosition) {
// 如果有保存的滚动位置(例如点击浏览器的前进/后退),则恢复
if (savedPosition) {
return savedPosition
} else {
// 否则滚动到顶部
return { top: 0 }
}
}
})
5.4 通过 URL 传递查询参数 (Query Parameters)
除了路径参数(params),还有查询参数(query)。
// 跳转到 /search?keyword=vue
router.push({ path: ‘/search’, query: { keyword: ‘vue’ } })
在组件中获取:
const route = useRoute()
console.log(route.query.keyword)
6. 常见问题排查 (Troubleshooting)
6.1 404 错误:刷新页面时报错
现象
:在开发环境或生产环境中,直接访问某个深层路径(如
/dashboard/settings
)或刷新该页面时,服务器返回 404。
原因
:Vue Router 使用的是单页面应用(SPA)路由机制。当服务器收到
/dashboard/settings
的请求时,它试图在服务器文件系统中寻找该路径对应的文件,但该文件不存在(它是由 Vue 客户端路由处理的)。
解决方案
:
需要配置服务器,将所有未知路径重定向到
index.html
。
Nginx
:
location / {
try_files $uri $uri/ /index.html;
}
Apache
: 在
.htaccess
文件中添加:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
Vue CLI 开发服务器
: 确保
vue.config.js
中的
publicPath
设置正确。
6.2 导航守卫死循环
现象
:页面白屏,控制台不断刷新或报错。
原因
:在
beforeEach
守卫中,调用
next()
时不小心再次触发了相同的路由,或者重定向的路由依然满足守卫条件,导致无限递归。
错误示例
:
router.beforeEach((to, from, next) => {
if (!isAuthenticated) {
// 如果 /login 也被守卫拦截,且没有正确处理,就会死循环
next(‘/login’)
} else {
next()
}
})
解决方案
:
在重定向前判断目标路由是否是当前路由,或者在守卫中排除某些路由(如登录页)。
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem(‘token’)
if (to.meta.requiresAuth && !isAuthenticated) {
// 如果目标已经是登录页,避免死循环
if (to.path === ‘/login’) {
next()
} else {
next(‘/login’)
}
} else {
next()
}
})
6.3 组件复用导致数据不更新
现象
:从
/user/1
点击链接跳转到
/user/2
,URL 变了,但页面显示的还是用户 1 的数据。
原因
:如前文所述,组件被复用了,
created
或
mounted
钩子没有再次执行。
解决方案
:
使用
watch
监听
route.params
的变化,或者使用
beforeRouteUpdate
守卫来触发数据更新。
6.4 Vue 2 到 Vue 3 (Vue Router 4) 的迁移痛点
new VueRouter
->
createRouter
: 创建方式改变。
mode: ‘history’
->
history: createWebHistory()
: 配置属性改变。
this.$route
->
useRoute()
: 组合式 API 中不再有
this
。
this.$router
->
useRouter()
: 同上。
的
tag
属性被移除
: 现在使用
v-slot
来自定义渲染。
About
7. 总结
Vue Router 4 提供了强大而灵活的 API 来管理 Vue 3 应用的路由。掌握基础配置、动态路由参数的处理、嵌套路由的组织以及导航守卫的运用,是构建复杂单页面应用的基石。通过合理利用懒加载、过渡效果和滚动行为控制,可以极大地提升用户体验。遇到问题时,仔细检查服务器配置和守卫逻辑,通常能快速定位并解决。