Vue 2.x 与 Vue 3.x 路由差异及迁移指南

一、核心差异概述

Vue Router 4.x 作为 Vue 3 的官方路由解决方案,在 API 设计上保持了与 3.x 版本的高度相似性,但仍有几个关键差异需要注意:

图1

二、API 变化详解

1. 路由创建方式

Vue 2.x (Router 3.x):

import VueRouter from 'vue-router'

const router = new VueRouter({
  routes: [...]
})

Vue 3.x (Router 4.x):

import { createRouter } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(), // 必须明确指定history模式
  routes: [...]
})

2. 路由模式定义

  • new VueRouter({ mode: 'hash' })createRouter({ history: createWebHashHistory() })
  • mode: 'history'history: createWebHistory()
  • mode: 'abstract'history: createMemoryHistory()

3. 动态路由匹配变化

移除* 通配符路由,改为必须使用带有自定义正则的参数:

// 3.x
{ path: '*' }

// 4.x
{ path: '/:pathMatch(.*)*' }

4. 路由守卫调整

next 函数变为可选参数,可以通过返回以下值控制导航:

// 显式调用next (兼容模式)
beforeEach((to, from, next) => {
  next()
})

// 新推荐方式 (返回控制)
beforeEach(async (to, from) => {
  // 返回false取消导航
  // 返回路由路径字符串重定向
  // 不返回或返回undefined继续导航
})

三、迁移步骤指南

1. 依赖升级

npm uninstall vue-router
npm install vue-router@4

2. 入口文件改造

// main.js/ts
import { createApp } from 'vue'
import { createRouter } from 'vue-router'

const app = createApp(App)
const router = createRouter({...})
app.use(router)

3. 常见模式迁移示例

路由重定向:

// 3.x
{ path: '/old', redirect: '/new' }

// 4.x (保持相同)
{ path: '/old', redirect: '/new' }

别名配置:

// 3.x
{ path: '/home', alias: '/' }

// 4.x (保持相同但行为更一致)
{ path: '/home', alias: ['/'] }

四、Composition API 集成

Vue Router 4.x 提供了完整的 Composition API 支持:

import { useRoute, useRouter } from 'vue-router'

export default {
  setup() {
    const route = useRoute() // 相当于this.$route
    const router = useRouter() // 相当于this.$router
    
    const navigate = () => {
      router.push({
        path: '/new',
        query: { ...route.query } // 保留现有查询参数
      })
    }
    
    return { navigate }
  }
}

五、迁移检查清单

  1. [ ] 更新 package.json 中的 vue-router 版本
  2. [ ] 替换所有 new VueRouter()createRouter()
  3. [ ] 显式指定 history 模式
  4. [ ] 检查通配符路由是否使用新语法
  5. [ ] 测试所有导航守卫逻辑
  6. [ ] 更新单元测试中的模拟路由
  7. [ ] 检查 TypeScript 类型定义(如适用)

六、实践建议

  1. 渐进式迁移:对于大型项目,考虑逐步迁移路由模块
  2. 类型安全:在 TypeScript 项目中充分利用新的类型定义
  3. 性能优化:利用 4.x 改进的懒加载功能

    {
      path: '/dashboard',
      component: () => import(/* webpackChunkName: "dashboard" */ './views/Dashboard.vue')
    }
  4. 守卫简化:尽可能使用新的守卫返回值语法

七、常见问题解决

Q: 迁移后路由跳转不生效?
A: 确保在 4.x 中所有导航都是通过 router 实例进行的,Vue 3 不再自动注入 $router

Q: 通配符路由失效?
A: 确认已将所有 * 替换为 /:pathMatch(.*)*

Q: 测试用例报错?
A: 更新测试中的路由模拟,参考官方测试示例:

import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
  history: createWebHistory(),
  routes: []
})

通过以上步骤,您可以顺利完成从 vue-router 3.x 到 4.x 的迁移,同时充分利用 Vue 3 的新特性提升应用的路由体验。

评论已关闭