本篇定位:路由是构建单页应用(SPA)的核心基础设施。本篇将系统讲解 Vue Router 4 的安装配置、路由定义、导航方式、动态路由匹配等核心概念。读完本篇,你将能够为 Vue 应用搭建完整的路由系统,实现页面之间的流畅切换。
一、什么是路由?
1.1 路由的基本概念
在 Web 开发中,路由(Routing) 指的是根据 URL 地址决定渲染哪个页面或组件的机制。
传统多页应用(MPA):
用户点击链接 → 浏览器向服务器发送请求 → 服务器返回完整 HTML 页面 → 浏览器刷新加载
单页应用(SPA):
用户点击链接 → JavaScript 拦截 → 切换显示组件 → 更新 URL(不刷新页面)
Vue Router 是 Vue 官方提供的路由管理器,它与 Vue 核心深度集成,使得构建 SPA 变得简单直观。
1.2 Vue Router 的核心功能
| 功能 | 说明 |
|---|---|
| 路由映射 | 将 URL 路径映射到对应的 Vue 组件 |
| 嵌套路由 | 支持在页面中嵌套子路由 |
| 导航守卫 | 在路由切换前后执行逻辑(权限验证、数据预加载等) |
| 路由懒加载 | 按需加载路由组件,优化首屏性能 |
| 路由参数 | 支持动态路径参数和查询参数 |
| 编程式导航 | 通过 JavaScript 代码控制路由跳转 |
| 过渡动画 | 路由切换时自动应用过渡效果 |
1.3 Vue Router 4 的主要变化
| 变化 | Vue Router 3 | Vue Router 4 |
|---|---|---|
| 创建方式 | new VueRouter() |
createRouter() |
| 历史模式 | mode: 'history' |
history: createWebHistory() |
| 路由匹配 | 基于 path-to-regexp |
基于新的匹配器(性能更好) |
| 导航守卫 | 需要调用 next() |
可直接返回值(next 可选) |
| TypeScript | 支持有限 | 原生支持,类型推导更好 |
二、安装与配置
2.1 安装 Vue Router
bash
# 使用 npm
npm install vue-router@4
# 使用 pnpm(推荐)
pnpm add vue-router@4
2.2 创建路由实例
typescript
// src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
// 定义路由配置
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// 路由懒加载
component: () => import('../views/AboutView.vue')
}
]
// 创建路由实例
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes
})
export default router
2.3 在 Vue 应用中注册路由
typescript
// src/main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router) // 注册路由插件
app.mount('#app')
2.4 路由模式对比
| 模式 | 创建方式 | URL 示例 | 适用场景 |
|---|---|---|---|
| HTML5 History | createWebHistory() |
example.com/about |
大多数现代应用(需服务器配置) |
| Hash 模式 | createWebHashHistory() |
example.com/#/about |
无需服务器配置,兼容性好 |
| Memory 模式 | createMemoryHistory() |
无 URL | 非浏览器环境(如 SSR、测试) |
History 模式需要服务器配置(Nginx 示例):
nginx
# nginx.conf
location / {
try_files $uri $uri/ /index.html;
}
Hash 模式无需特殊配置 ,但 URL 中包含 # 不够美观。
三、路由定义
3.1 基本路由
typescript
// src/router/index.ts
const routes = [
{
path: '/',
component: HomePage
},
{
path: '/about',
component: AboutPage
},
{
path: '/contact',
component: ContactPage
}
]
3.2 命名路由
为路由配置 name 属性,便于通过名称进行导航:
typescript
const routes = [
{
path: '/',
name: 'home',
component: HomePage
},
{
path: '/about',
name: 'about',
component: AboutPage
},
{
path: '/users/:id',
name: 'user-detail',
component: UserDetail
}
]
3.3 动态路由匹配
路径参数 :使用 : 标记动态片段
typescript
const routes = [
// 匹配 /users/1, /users/2 等
{
path: '/users/:id',
component: UserDetail
},
// 匹配 /posts/123/comments/456
{
path: '/posts/:postId/comments/:commentId',
component: CommentDetail
},
// 匹配 /files/any/path/here
{
path: '/files/:pathMatch(.*)*',
component: FileViewer
}
]
访问参数(在组件中):
vue
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
// 访问路径参数
console.log(route.params.id) // '123'
console.log(route.params.postId) // '456'
// 访问查询参数
console.log(route.query.keyword) // 'vue'
console.log(route.query.page) // '1'
</script>
参数变化时的响应:
vue
<script setup>
import { watch } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
// 侦听路由参数变化
watch(() => route.params.id, (newId) => {
// 当 id 变化时重新加载数据
fetchUserData(newId)
})
</script>
3.4 路由通配符与 404
typescript
const routes = [
// 匹配所有路径(用于 404 页面)
{
path: '/:pathMatch(.*)*',
name: 'not-found',
component: NotFoundView
}
]
// 或者更精确的匹配
const routes = [
{
path: '/:pathMatch(.*)*',
redirect: '/404'
},
{
path: '/404',
component: NotFoundView
}
]
3.5 路由重定向
typescript
const routes = [
// 重定向到命名路由
{
path: '/home',
redirect: { name: 'dashboard' }
},
// 重定向到指定路径
{
path: '/old-about',
redirect: '/about'
},
// 动态重定向(函数)
{
path: '/users/:id',
redirect: (to) => {
// 可以根据条件决定重定向目标
if (to.params.id === 'admin') {
return { name: 'admin-dashboard' }
}
return { name: 'user-profile' }
}
}
]
3.6 路由别名
typescript
const routes = [
{
path: '/dashboard',
component: DashboardPage,
alias: ['/admin', '/console'] // 多个别名
}
]
// /dashboard、/admin、/console 都渲染 DashboardPage
四、声明式导航:RouterLink
4.1 基本用法
vue
<template>
<!-- 使用路径跳转 -->
<RouterLink to="/">首页</RouterLink>
<RouterLink to="/about">关于</RouterLink>
<!-- 使用命名路由 -->
<RouterLink :to="{ name: 'user-detail', params: { id: 123 } }">
用户 123
</RouterLink>
<!-- 带查询参数 -->
<RouterLink :to="{ path: '/search', query: { keyword: 'vue', page: 1 } }">
搜索 Vue
</RouterLink>
<!-- 带 Hash -->
<RouterLink :to="{ path: '/about', hash: '#section-1' }">
关于 - 第一节
</RouterLink>
</template>
4.2 属性详解
| 属性 | 说明 | 示例 |
|---|---|---|
to |
目标路由地址 | to="/about" 或 :to="{ name: 'about' }" |
replace |
替换历史记录(不新增) | replace |
active-class |
激活时的 CSS 类名 | active-class="active" |
exact-active-class |
精确匹配时的 CSS 类名 | exact-active-class="exact-active" |
custom |
自定义渲染(不生成 <a> 标签) |
custom v-slot="{ navigate }" |
4.3 自定义激活样式
vue
<template>
<!-- 自定义 active 类名 -->
<RouterLink
to="/"
active-class="is-active"
exact-active-class="is-exact-active"
>
首页
</RouterLink>
</template>
<style>
.is-active {
color: #42b883;
font-weight: bold;
}
.is-exact-active {
border-bottom: 2px solid #42b883;
}
</style>
4.4 自定义渲染(高级)
vue
<script setup>
import { RouterLink } from 'vue-router'
</script>
<template>
<!-- 使用 v-slot 自定义渲染 -->
<RouterLink to="/about" custom v-slot="{ navigate, isActive, isExactActive }">
<button
@click="navigate"
:class="['custom-link', { active: isActive, exact: isExactActive }]"
>
📖 关于我们
<span v-if="isExactActive">(当前页面)</span>
</button>
</RouterLink>
<!-- 自定义导航标签 -->
<RouterLink to="/dashboard" custom v-slot="{ navigate }">
<div class="nav-item" @click="navigate">
<span class="icon">📊</span>
<span>控制台</span>
</div>
</RouterLink>
</template>
五、编程式导航
5.1 useRouter 和 useRoute
在组合式 API 中,通过 useRouter 和 useRoute 访问路由对象:
vue
<script setup>
import { useRouter, useRoute } from 'vue-router'
// 路由实例(用于导航)
const router = useRouter()
// 当前路由信息(只读)
const route = useRoute()
console.log('当前路径:', route.path)
console.log('当前参数:', route.params)
console.log('当前查询:', route.query)
</script>
5.2 router.push() ------ 跳转到新页面
vue
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
function goToHome() {
router.push('/')
}
function goToAbout() {
router.push({ path: '/about' })
}
function goToUser(id: number) {
router.push({ name: 'user-detail', params: { id } })
}
function search(keyword: string) {
router.push({ path: '/search', query: { keyword } })
}
// 添加 hash
function goToSection() {
router.push({ path: '/about', hash: '#section-1' })
}
</script>
5.3 router.replace() ------ 替换历史记录
push 会新增一条历史记录(可以后退),replace 不会新增(替换当前记录):
vue
<script setup>
function handleLogin() {
// 登录后跳转到首页,但不希望用户回到登录页
router.replace({ name: 'dashboard' })
}
function handleNotFound() {
// 404 页面跳转使用 replace
router.replace('/404')
}
</script>
5.4 router.go() / router.back() / router.forward()
vue
<script setup>
const router = useRouter()
// 后退一步
function goBack() {
router.back()
}
// 前进一步
function goForward() {
router.forward()
}
// 前进/后退指定步数
function goSteps(steps: number) {
router.go(steps) // -1 后退,1 前进
}
</script>
六、嵌套路由
6.1 基本概念
嵌套路由允许在页面内部嵌套子路由,实现复杂的布局结构:
/user/123/profile
├── /user/123 (UserLayout)
│ ├── /user/123/profile (UserProfile)
│ └── /user/123/settings (UserSettings)
6.2 定义嵌套路由
typescript
// src/router/index.ts
import UserLayout from '../views/UserLayout.vue'
import UserProfile from '../views/UserProfile.vue'
import UserSettings from '../views/UserSettings.vue'
const routes = [
{
path: '/user/:id',
component: UserLayout, // 父布局组件
children: [
{
path: '', // 匹配 /user/:id
component: UserProfile
},
{
path: 'profile', // 匹配 /user/:id/profile
component: UserProfile
},
{
path: 'settings', // 匹配 /user/:id/settings
component: UserSettings
}
]
}
]
6.3 RouterView 与嵌套渲染
vue
<!-- UserLayout.vue(父布局) -->
<template>
<div class="user-layout">
<header>
<h2>用户中心</h2>
<nav>
<RouterLink :to="{ name: 'user-profile' }">个人资料</RouterLink>
<RouterLink :to="{ name: 'user-settings' }">设置</RouterLink>
</nav>
</header>
<main>
<!-- 子路由组件渲染在此处 -->
<RouterView />
</main>
</div>
</template>
6.4 命名 RouterView
当需要在一个页面中显示多个路由视图时:
vue
<!-- 父组件 -->
<template>
<div class="layout">
<!-- 默认视图 -->
<RouterView />
<!-- 命名视图 -->
<RouterView name="sidebar" />
<RouterView name="footer" />
</div>
</template>
typescript
// 路由配置
const routes = [
{
path: '/dashboard',
components: {
default: DashboardMain,
sidebar: DashboardSidebar,
footer: DashboardFooter
}
}
]
6.5 嵌套路由的深度
typescript
const routes = [
{
path: '/shop',
component: ShopLayout,
children: [
{
path: 'products',
component: ProductList,
children: [
{
path: ':id', // /shop/products/123
component: ProductDetail
}
]
},
{
path: 'cart', // /shop/cart
component: ShoppingCart
}
]
}
]
渲染结构:
<ShopLayout> <!-- 第一层 -->
<ProductList> <!-- 第二层 -->
<ProductDetail /> <!-- 第三层 -->
</ProductList>
</ShopLayout>
七、路由懒加载
7.1 基本用法
路由懒加载利用 Webpack/Vite 的代码分割功能,按需加载路由组件:
typescript
// ❌ 不推荐:所有组件打包在一起
import HomePage from './views/HomePage.vue'
import AboutPage from './views/AboutPage.vue'
const routes = [
{ path: '/', component: HomePage },
{ path: '/about', component: AboutPage }
]
// ✅ 推荐:路由懒加载
const routes = [
{ path: '/', component: () => import('./views/HomePage.vue') },
{ path: '/about', component: () => import('./views/AboutPage.vue') }
]
7.2 命名 Chunk
typescript
// 使用 webpackChunkName 注释指定 chunk 名称
const routes = [
{
path: '/admin',
component: () => import(/* webpackChunkName: "admin" */ './views/AdminPage.vue')
},
{
path: '/dashboard',
component: () => import(/* webpackChunkName: "dashboard" */ './views/DashboardPage.vue')
}
]
7.3 预加载优化
typescript
// 使用 webpackPreload 预加载关键路由
const routes = [
{
path: '/',
component: () => import(/* webpackPreload: true */ './views/HomePage.vue')
}
]
八、综合实战:完整的路由配置
typescript
// src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
// 定义路由
const routes: RouteRecordRaw[] = [
// 首页
{
path: '/',
name: 'home',
component: () => import('../views/HomeView.vue'),
meta: {
title: '首页',
requiresAuth: false
}
},
// 关于页面
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue'),
meta: {
title: '关于我们'
}
},
// 用户模块(嵌套路由)
{
path: '/user',
component: () => import('../views/user/UserLayout.vue'),
meta: {
requiresAuth: true
},
children: [
{
path: 'profile',
name: 'user-profile',
component: () => import('../views/user/UserProfile.vue'),
meta: { title: '个人资料' }
},
{
path: 'settings',
name: 'user-settings',
component: () => import('../views/user/UserSettings.vue'),
meta: { title: '设置' }
},
{
path: 'orders',
name: 'user-orders',
component: () => import('../views/user/UserOrders.vue'),
meta: { title: '我的订单' }
}
]
},
// 产品模块
{
path: '/products',
name: 'products',
component: () => import('../views/products/ProductList.vue'),
meta: { title: '产品列表' }
},
{
path: '/products/:id',
name: 'product-detail',
component: () => import('../views/products/ProductDetail.vue'),
meta: { title: '产品详情' }
},
// 搜索页面
{
path: '/search',
name: 'search',
component: () => import('../views/SearchView.vue'),
meta: { title: '搜索' }
},
// 登录页面
{
path: '/login',
name: 'login',
component: () => import('../views/LoginView.vue'),
meta: {
title: '登录',
requiresGuest: true // 仅访客可访问
}
},
// 404 页面
{
path: '/404',
name: 'not-found',
component: () => import('../views/NotFoundView.vue'),
meta: { title: '页面未找到' }
},
// 通配符重定向到 404
{
path: '/:pathMatch(.*)*',
redirect: '/404'
}
]
// 创建路由实例
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes,
// 滚动行为
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
}
return { top: 0, behavior: 'smooth' }
}
})
// 导航守卫:设置页面标题
router.beforeEach((to, from) => {
const title = to.meta?.title as string
if (title) {
document.title = `${title} - My App`
}
})
// 导航守卫:权限验证
router.beforeEach((to, from) => {
const requiresAuth = to.meta?.requiresAuth as boolean
const requiresGuest = to.meta?.requiresGuest as boolean
const isLoggedIn = !!localStorage.getItem('token')
if (requiresAuth && !isLoggedIn) {
// 需要登录,跳转到登录页
return { name: 'login', query: { redirect: to.fullPath } }
}
if (requiresGuest && isLoggedIn) {
// 已登录用户不能访问登录页
return { name: 'home' }
}
})
export default router
使用路由的 App 组件:
vue
<!-- src/App.vue -->
<script setup>
import { RouterView, RouterLink } from 'vue-router'
</script>
<template>
<div class="app">
<header class="app-header">
<RouterLink to="/" class="logo">My App</RouterLink>
<nav>
<RouterLink to="/">首页</RouterLink>
<RouterLink to="/products">产品</RouterLink>
<RouterLink to="/about">关于</RouterLink>
<RouterLink to="/user/profile">个人中心</RouterLink>
</nav>
</header>
<main class="app-main">
<RouterView v-slot="{ Component, route }">
<Transition name="fade" mode="out-in">
<component :is="Component" :key="route.fullPath" />
</Transition>
</RouterView>
</main>
<footer class="app-footer">
<p>© 2026 My App</p>
</footer>
</div>
</template>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
九、常见问题与解决方案
9.1 路由参数变化但页面不更新
问题 :/user/1 → /user/2,组件被复用,数据未刷新。
解决方案:
vue
<script setup>
import { watch } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
// 侦听参数变化
watch(() => route.params.id, (newId) => {
fetchData(newId)
}, { immediate: true })
</script>
9.2 路由守卫中的异步操作
typescript
router.beforeEach(async (to, from) => {
const token = localStorage.getItem('token')
if (to.meta.requiresAuth && !token) {
return '/login'
}
// 异步验证
if (to.meta.requiresAuth && token) {
const isValid = await validateToken(token)
if (!isValid) {
localStorage.removeItem('token')
return '/login'
}
}
})
9.3 滚动行为异常
typescript
// 控制滚动行为
const router = createRouter({
// ...
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
}
// 滚动到顶部
return { top: 0, behavior: 'smooth' }
}
})
9.4 路由守卫重复触发
避免在守卫中调用 router.push 导致无限循环:
typescript
router.beforeEach((to, from) => {
const isLoggedIn = !!localStorage.getItem('token')
if (to.meta.requiresAuth && !isLoggedIn) {
// 检查是否已经在登录页
if (to.name === 'login') {
return true
}
return { name: 'login' }
}
})
十、本篇小结
| 知识点 | 核心内容 |
|---|---|
| 路由创建 | createRouter({ history, routes }) |
| 历史模式 | createWebHistory()、createWebHashHistory() |
| 路由定义 | path、name、component、children |
| 动态路由 | :id、:postId/:commentId、正则匹配 |
| 导航方式 | 声明式 RouterLink、编程式 router.push() |
| 参数访问 | useRoute() 获取 params 和 query |
| 嵌套路由 | children + RouterView |
| 懒加载 | () => import('./Component.vue') |
十一、思考与练习
-
基础练习:创建一个包含首页、关于页、用户页的 Vue 项目,配置 Vue Router 实现页面切换。
-
实践任务 :在用户页中实现嵌套路由,包含个人资料、设置、订单三个子页面,并使用
RouterLink和RouterView实现导航切换。 -
深度思考 :
router.push和router.replace的区别是什么?在什么场景下应该使用replace? -
扩展任务:为路由添加权限守卫,实现未登录用户访问需登录页面时自动跳转到登录页,登录后返回原页面。
下篇预告
第 21 篇我们将继续 Vue Router 的学习------路由管理完全指南(下):
- 路由守卫(全局、路由独享、组件内)
- 路由元信息与权限控制
- 路由过渡动画
- 路由懒加载优化
- 动态路由添加
准备好掌握 Vue Router 的高级特性!🔐