1593 字
约 5 分钟
1
Vue Router 进阶教程:Vue 3 全家桶路由管理实战指南

Vue Router 进阶教程:Vue 3 全家桶路由管理实战指南

Vue Router 是 Vue.js 官方提供的路由管理库,用于构建单页应用(SPA)。它帮助开发者实现 URL 与 Vue 组件之间的映射,管理浏览器的历史记录,并提供丰富的导航和守卫机制。

本教程将从基础概念出发,逐步深入到高级特性,帮助你掌握 Vue Router 的核心用法和最佳实践。

1. Vue Router 基础回顾

1.1 核心概念

Vue Router 的核心组件包括:

  • 路由配置(Routes):定义 URL 路径与组件的映射
  • 路由导航(Router-link):声明式导航组件
  • 路由出口(Router-view):动态渲染匹配路由的组件
  • 路由实例:通过 useRouter()this.$router 获取实例

1.2 基本安装与配置

npm install vue-router@4

main.js 注册路由

import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import Home from '@/views/Home.vue'
import About from '@/views/About.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

const app = createApp(App)
app.use(router)
app.mount('#app')

App.vue 模板使用

<template>
  <nav>
    <router-link to="/">首页</router-link>
    <router-link to="/about">关于</router-link>
  </nav>
  <router-view></router-view>
</template>

2. 路由模式与高级配置

2.1 路由模式选择

  • history 模式:使用 HTML5 History API(推荐生产环境)
  • hash 模式:使用 # 符号的 URL(适用于静态服务器)
  • abstract 模式:支持 Node.js 环境
// 生产环境推荐使用 history 模式
const router = createRouter({
  history: createWebHistory(),
  routes: [...]
})

// 测试环境或静态部署使用 hash 模式
const router = createRouter({
  history: createWebHashHistory(),
  routes: [...]
})

2.2 路由元信息

为路由添加自定义元信息,用于权限控制等:

const routes = [
  {
    path: '/admin',
    component: Admin,
    meta: { 
      requiresAuth: true,
      roles: ['admin']
    }
  }
]

2.3 懒加载路由(推荐)

提升应用初始加载速度:

{
  path: '/about',
  component: () => import('@/views/About.vue')
}

2.4 404 错误页处理

{
  path: '/:pathMatch(.*)*',
  component: NotFound
}

3. 路由导航与匹配

3.1 声明式导航

<router-link to="/about" replace>关于我们</router-link>

<!-- 动态路由 -->
<router-link :to="{ name: 'User', params: { id: 123 } }">
  用户详情
</router-link>

3.2 编程式导航

// 获取路由实例
const router = useRouter()

// 普通跳转
router.push('/about')

// 替换历史记录(不保留历史)
router.replace('/about')

// 携带参数
router.push({ name: 'User', params: { id: 123 } })

// 携带查询参数
router.push({ path: '/search', query: { q: 'vue' } })

// 返回上一页
router.go(-1)

3.3 路由匹配规则

Vue Router 使用路径匹配,支持:

  • 静态路由/about
  • 动态路由/user/:id
  • 通配符路由/:pathMatch(.*)

4. 路由守卫(Vue Router 4 新特性)

4.1 全局前置守卫

const router = createRouter({
  history: createWebHistory(),
  routes: [...]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 登录验证
  if (to.path === '/admin' && !store.state.isAdmin) {
    next('/login')
    return
  }
  
  // 添加进度条
  NProgress.start()
  next()
})

// 全局后置守卫
router.afterEach((to, from) => {
  NProgress.done()
})

4.2 路由独享守卫

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    // 可以直接在这里使用
    next()
  } else {
    next()
  }
})

4.3 组件内守卫

// 在组件中使用
export default {
  beforeRouteEnter(to, from, next) {
    // 仅在导航前可用
    next()
  },
  beforeRouteUpdate(to, from, next) {
    // 路由改变时触发
    next()
  },
  beforeRouteLeave(to, from, next) {
    // 离开当前路由时触发
    next()
  }
}

4.4 组合式 API 守卫

import { onBeforeRouteEnter, onBeforeRouteUpdate, onBeforeRouteLeave } from 'vue-router'

export default {
  setup() {
    onBeforeRouteEnter((to, from, next) => {
      // ...
      next()
    })
    onBeforeRouteUpdate((to, from) => {
      // ...
    })
    onBeforeRouteLeave((to, from) => {
      // ...
    })
    // ...
  }
}

5. 嵌套路由与动态路由

5.1 嵌套路由

const routes = [
  {
    path: '/user',
    component: UserLayout,
    children: [
      { path: '', component: UserHome },
      { path: 'profile', component: UserProfile }
    ]
  }
]

模板使用

<router-view></router-view> <!-- 渲染 UserLayout 内部的子路由 -->

5.2 动态路由

{
  path: '/user/:id',
  component: UserDetail,
  props: true, // 自动将路由参数作为 props 传递
  children: [
    {
      path: 'posts',
      component: UserPosts
    }
  ]
}

获取参数

// 使用 props
props: ['userId']

// 使用 useRoute
const route = useRoute()
console.log(route.params.id)

6. 路由动画与过渡效果

6.1 配置路由动画

router.beforeEach((to, from, next) => {
  // 启动动画
  next()
})

CSS 过渡

<transition name="fade" mode="out-in">
  <router-view></router-view>
</transition>

CSS 样式

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

6.2 使用 Vue Transitions

<transition name="slide" mode="out-in">
  <router-view></router-view>
</transition>

7. 数据获取前置守卫

对于需要在路由切换前获取数据的场景:

router.beforeEach((to, from, next) => {
  if (to.path === '/dashboard') {
    // 在这里可以获取数据
    store.dispatch('fetchUserProfile')
  }
  next()
})

8. 高级特性

8.1 滚动行为

const router = createRouter({
  history: createWebHistory(),
  routes: [...],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

8.2 路由标签页

router.beforeEach((to, from, next) => {
  document.title = `我的网站 - ${to.meta.title || '首页'}`
  next()
})

8.3 自定义路由扩展

const customRouter = createRouter({
  history: createWebHistory(),
  routes: [...]
})

// 扩展方法
customRouter.myMethod = function() {
  // 自定义功能
}

9. 最佳实践

  1. 使用懒加载提高首屏加载速度
  2. 合理使用路由守卫进行权限控制
  3. 避免在全局守卫中做耗时操作
  4. 使用组合式 API 代替选项式 API
  5. 为路由添加元信息 便于复用
  6. 考虑使用 Vue Router 的新特性useRouteuseRouter

10. 常见问题解决

Q1: 路由重复点击报错

解决

const router = createRouter({...})
router.onError((error) => {
  if (error.message.includes('NavigationDuplicated')) {
    // 忽略重复导航错误
  }
})

Q2: 如何传递数据到目标路由?

  • 使用 query 传递:router.push({ path: '/search', query: { q: 'vue' } })
  • 使用 params + 动态路由

Q3: 如何在路由守卫中获取组件实例?

  • 使用 next(to, from, next) 中的 to 信息

总结

Vue Router 作为 Vue 生态系统的核心路由解决方案,为构建 SPA 提供了强大的支持。通过学习本教程,你可以掌握:

  • 基本配置与导航
  • 高级路由特性
  • 路由守卫机制
  • 动画与过渡
  • 最佳实践

祝你使用愉快!

推荐阅读


本文由 Clarity 学习台 AI 助手生成

Vue Router 进阶教程:Vue 3 全家桶路由管理实战指南
http://clxhxhhr.top/posts/335/
作者
clxstart
发布于
2026-08-22
许可协议
CC BY-NC-SA 4.0
评论
0 条
还没有评论,先写一条吧。