Vue2极简教程004-vue-router的使用
Vue2极简教程004:vue-router 核心使用指南
一、安装与基础配置
1. 安装vue-router
npm install vue-router@3 # Vue2必须使用3.x版本
2. 初始化路由配置
// src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue') // 路由懒加载
}
]
const router = new VueRouter({
mode: 'history', // 可选hash模式
base: process.env.BASE_URL,
routes
})
export default router
3. 挂载到Vue实例
// main.js
import router from './router'
new Vue({
router, // 注入路由
render: h => h(App)
}).$mount('#app')
二、核心功能实践
1. 路由导航方式
<!-- 模板中使用 -->
<router-link to="/about">关于我们</router-link>
<router-link :to="{ name: 'About' }">命名路由</router-link>
<!-- 编程式导航 -->
<script>
export default {
methods: {
goToAbout() {
this.$router.push('/about')
// 等价于
this.$router.push({ name: 'About' })
}
}
}
</script>
2. 动态路由匹配
// 路由配置
{
path: '/user/:id',
name: 'User',
component: () => import('../views/User.vue'),
props: true // 将params转为props
}
// 组件中获取
export default {
props: ['id'],
created() {
console.log(this.id) // 获取路由参数
}
}
3. 嵌套路由
{
path: '/',
redirect: '/dashboard', // 路由重定向,当点击首页重定向到 /dashboard
component: Dashboard,
children: [
{
path: '', // 默认子路由
component: DashboardHome
},
{
path: 'settings',
component: DashboardSettings
}
]
}
三、高级功能配置
1. 路由守卫
// 全局前置守卫
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
next('/login')
} else {
next()
}
})
// 路由独享守卫
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
// 校验逻辑
}
}
// 组件内守卫
export default {
beforeRouteEnter(to, from, next) {
// 不能访问this
next(vm => {
// 通过vm访问组件实例
})
}
}
2. 路由元信息
{
path: '/profile',
meta: {
requiresAuth: true,
title: '用户中心'
}
}
// 动态修改标题
router.beforeEach((to, from, next) => {
document.title = to.meta.title || '默认标题'
next()
})
3. 滚动行为控制
const router = new VueRouter({
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition // 返回保存的位置
}
return { x: 0, y: 0 } // 滚动到顶部
}
})
四、项目结构建议
src/
├── router/
│ ├── index.js # 路由入口
│ ├── routes/ # 路由模块拆分
│ │ ├── auth.js # 认证相关路由
│ │ ├── admin.js # 管理后台路由
│ └── guards.js # 路由守卫
├── views/ # 路由级组件
│ ├── Home.vue
│ └── About.vue
└── components/ # 普通组件
五、常见问题解决方案
1. 路由重复导航报错
// 重写push方法
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
2. 动态添加路由
// 添加新路由
router.addRoute({
path: '/new',
component: () => import('@/views/New.vue')
})
// 添加嵌套路由
router.addRoute('parentRoute', {
path: 'child',
component: () => import('@/views/Child.vue')
})
3. 404页面处理
// 放在路由配置最后
{
path: '*',
component: () => import('@/views/NotFound.vue')
}
六、性能优化建议
路由懒加载:
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
预加载策略:
// 在主要页面加载后预加载其他路由 mounted() { import('../views/Contact.vue') }
路由分块:
// webpack配置修改 output: { chunkFilename: '[name].[chunkhash].js' }
版本提示:本教程基于vue-router 3.x版本,Vue3项目请使用vue-router 4.x
通过合理配置vue-router,你可以实现:
- 清晰的URL结构管理
- 模块化的路由配置
- 完善的导航控制
- 优雅的权限验证流程
建议配合Vue DevTools的Routing标签调试路由状态