Vue Router 2 完全教程

安装与配置

1. 安装 Vue Router

在开始使用 Vue Router 之前,需要先安装它。你可以通过 npm 或 yarn 来安装:

安装 Vue Router

使用 npm 安装
npm install vue-router@3
使用 yarn 安装
yarn add vue-router@3

2. 在项目中引入 Vue Router

安装完成后,需要在项目中引入并配置 Vue Router。

配置 Vue Router

src/main.js
import Vue from 'vue' import App from './App.vue' import router from './router' Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app')
src/router/index.js
import Vue from 'vue' import VueRouter from 'vue-router' // 引入路由组件 import Home from '../views/Home.vue' import About from '../views/About.vue' // 使用 Vue Router Vue.use(VueRouter) // 定义路由配置 const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', component: About } ] // 创建路由实例 const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router

3. 项目结构

建议按照以下结构组织你的项目:

项目结构
src/ ├── router/ │ ├── index.js # 路由配置文件 │ └── routes.js # 路由定义文件(可选) ├── views/ │ ├── Home.vue # 首页组件 │ ├── About.vue # 关于页面组件 │ └── ... # 其他页面组件 ├── components/ # 可复用组件 ├── App.vue # 根组件 └── main.js # 入口文件

注意事项

第一章:Vue Router 基础概念

1.1 Vue Router 是什么?

Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。

练习 1.1:基本路由配置

创建一个简单的路由应用,包含首页和关于页面。

router/index.js
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import About from '../views/About.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', component: About } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
App.vue
<template> <div id="app"> <nav> <router-link to="/">首页</router-link> | <router-link to="/about">关于</router-link> </nav> <router-view/> </div> </template> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>

第二章:核心概念

2.1 动态路由

动态路由允许我们根据不同的参数渲染相同的组件。

练习 2.1:用户详情页

创建一个用户详情页,通过用户ID动态加载用户信息。

router/index.js (动态路由配置)
const routes = [ // ...其他路由 { path: '/user/:id', name: 'User', component: () => import('../views/User.vue'), props: true } ]
views/User.vue
<template> <div> <h2>用户详情</h2> <p>用户ID: {{ id }}</p> <p>用户名: {{ user.name }}</p> </div> </template> <script> export default { props: ['id'], data() { return { user: null } }, created() { // 模拟获取用户数据 this.fetchUserData() }, methods: { fetchUserData() { // 实际项目中应该从API获取数据 this.user = { id: this.id, name: '用户' + this.id } } } } </script>

2.2 嵌套路由

嵌套路由允许我们在一个路由组件中嵌套其他路由组件。

练习 2.2:用户管理页面

创建一个用户管理页面,包含用户列表和用户详情两个子页面。

router/index.js (嵌套路由配置)
const routes = [ { path: '/users', component: () => import('../views/Users.vue'), children: [ { path: '', name: 'UserList', component: () => import('../views/UserList.vue') }, { path: ':id', name: 'UserDetail', component: () => import('../views/UserDetail.vue'), props: true } ] } ]
views/Users.vue
<template> <div> <h2>用户管理</h2> <router-view/> </div> </template>

2.3 编程式导航

除了使用 router-link 创建导航链接,我们还可以使用 router 实例的方法进行编程式导航。

练习 2.3:登录后跳转

实现登录成功后跳转到用户主页的功能。

views/Login.vue
<template> <div> <h2>登录</h2> <button @click="login">登录</button> </div> </template> <script> export default { methods: { login() { // 模拟登录成功 this.$router.push({ name: 'User', params: { id: 1 } }) } } } </script>

2.4 路由守卫

路由守卫用于在路由跳转前后进行一些操作,如权限验证、数据预加载等。

练习 2.4:路由权限控制

实现一个需要登录才能访问的页面。

router/index.js (路由守卫配置)
const router = new VueRouter({ routes }) router.beforeEach((to, from, next) => { const isAuthenticated = localStorage.getItem('token') if (to.meta.requiresAuth && !isAuthenticated) { next({ name: 'Login', query: { redirect: to.fullPath } }) } else { next() } }) export default router
路由配置示例
const routes = [ { path: '/dashboard', name: 'Dashboard', component: () => import('../views/Dashboard.vue'), meta: { requiresAuth: true } } ]

2.5 路由元信息

路由元信息允许我们在路由配置中添加自定义数据。

练习 2.5:页面标题管理

实现根据路由自动更新页面标题的功能。

router/index.js (元信息配置)
const routes = [ { path: '/', name: 'Home', component: Home, meta: { title: '首页' } }, { path: '/about', name: 'About', component: About, meta: { title: '关于我们' } } ] router.beforeEach((to, from, next) => { document.title = to.meta.title || '默认标题' next() })

第三章:综合案例

3.1 电商网站路由设计

通过一个完整的电商网站案例,综合运用 Vue Router 的所有核心概念。

练习 3.1:电商网站路由实现

实现以下功能:

router/index.js (电商路由配置)
const routes = [ { path: '/', name: 'Home', component: () => import('../views/Home.vue') }, { path: '/products', component: () => import('../views/Products.vue'), children: [ { path: '', name: 'ProductList', component: () => import('../views/ProductList.vue') }, { path: ':id', name: 'ProductDetail', component: () => import('../views/ProductDetail.vue'), props: true } ] }, { path: '/cart', name: 'Cart', component: () => import('../views/Cart.vue'), meta: { requiresAuth: true } }, { path: '/user', component: () => import('../views/User.vue'), meta: { requiresAuth: true }, children: [ { path: '', name: 'UserProfile', component: () => import('../views/UserProfile.vue') }, { path: 'orders', name: 'UserOrders', component: () => import('../views/UserOrders.vue') } ] } ]

第四章:最佳实践

4.1 路由懒加载

使用路由懒加载可以优化应用的加载性能。

路由懒加载示例
const routes = [ { path: '/about', name: 'About', // 使用动态导入实现懒加载 component: () => import('../views/About.vue') } ]

4.2 滚动行为

自定义路由切换时的滚动行为。

滚动行为配置
const router = new VueRouter({ routes, scrollBehavior(to, from, savedPosition) { if (savedPosition) { return savedPosition } else { return { x: 0, y: 0 } } } })

4.3 路由过渡效果

为路由切换添加过渡动画。

路由过渡示例
<template> <div id="app"> <transition name="fade" mode="out-in"> <router-view/> </transition> </div> </template> <style> .fade-enter-active, .fade-leave-active { transition: opacity .5s; } .fade-enter, .fade-leave-to { opacity: 0; } </style>

第五章:常见问题解答

5.1 常见错误

列举并解决使用 Vue Router 时常见的错误。

常见错误及解决方案
// 错误1:重复导航到当前位置 // ❌ 错误做法 this.$router.push('/current-path') // ✅ 正确做法 if (this.$route.path !== '/current-path') { this.$router.push('/current-path') } // 错误2:忘记处理路由守卫的next // ❌ 错误做法 router.beforeEach((to, from, next) => { if (condition) { next('/login') } }) // ✅ 正确做法 router.beforeEach((to, from, next) => { if (condition) { next('/login') } else { next() } }) // 错误3:动态路由参数变化时组件不更新 // ❌ 错误做法 created() { this.fetchData() } // ✅ 正确做法 watch: { '$route.params.id': { handler: 'fetchData', immediate: true } }

5.2 调试技巧

介绍 Vue Router 的调试工具和技巧。

调试技巧示例
// 1. 在组件中打印路由信息 export default { created() { console.log('当前路由:', this.$route) console.log('路由实例:', this.$router) } } // 2. 使用 Vue Devtools 查看路由状态 // 在 main.js 中配置 import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) // 3. 监听路由变化 export default { watch: { '$route'(to, from) { console.log('路由从', from.path, '变化到', to.path) } } }

学习建议

建议按照章节顺序学习,每完成一个练习后再进行下一个。遇到问题时,可以查看对应的常见问题解答部分。