Vue 3 和 Vue 2 的路由(Vue Router)有非常明显的变化。
最核心的区别在于版本不兼容:Vue 3 必须搭配 Vue Router 4.x 使用,而 Vue 2 使用的是 Vue Router 3.x。
Vue 3 的路由在设计上更现代化,全面拥抱了组合式 API(Composition API)和 TypeScript。以下是两者在实际开发中最主要的几个区别:
- 路由实例的创建方式不同
Vue 2 采用传统的构造函数,而 Vue 3 改用了更符合函数式编程思想的工厂函数。
* Vue 2 (Vue Router 3):使用 new VueRouter() 创建,通过 mode 属性来配置模式。
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter) // 必须显式注册插件
const router = new VueRouter({
mode: 'history', // 或 'hash'
routes: [...]
})
* Vue 3 (Vue Router 4):使用 createRouter() 创建,通过引入 createWebHistory 等函数来配置模式。
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(), // 或 createWebHashHistory()
routes: [...]
})
- 组件内获取路由对象的方式不同(最常用)
在 Vue 3 的组合式 API(<script setup>)中,无法再使用 this,因此获取路由的方式发生了巨大变化。
* Vue 2 (选项式 API):通过 this.router(路由实例)和 this.route(当前路由信息)来访问。
export default {
methods: {
goBack() {
this.router.go(-1)
}
},
mounted() {
console.log(this.route.params.id)
}
}
* Vue 3 (组合式 API):必须引入并使用 useRouter 和 useRoute 这两个 Hooks。
<script setup>
import { useRouter, useRoute } from 'vue-router'
const router = useRouter() // 用于路由跳转等操作
const route = useRoute() // 用于获取当前路由参数等信息
const goBack = () => {
router.go(-1)
}
console.log(route.params.id)
</script>
- 导航守卫中 next 函数的变化
在全局前置守卫(beforeEach)中,Vue 3 简化了流程控制。
* Vue 2:必须调用 next() 函数来 resolve 这个钩子,否则路由跳转就会被卡住。
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
next('/login') // 跳转到登录页
} else {
next() // 继续正常跳转
}
})
* Vue 3:next 函数变为可选。你可以直接通过 return 来控制导航(返回 false 取消导航,返回路径字符串进行重定向,不返回或返回 true 则继续)。
router.beforeEach((to, from) => {
if (to.meta.requiresAuth) {
return '/login' // 直接返回路径进行重定向
}
// 不返回或返回 true 表示通过
})
- 404 通配符路由的写法不同
由于底层依赖的路径匹配库升级,捕获所有未匹配路由(404页面)的写法也变了。
* Vue 2:使用 * 通配符。
{ path: '*', component: NotFound }
* Vue 3:使用带有自定义正则的动态路由参数。
{ path: '/:pathMatch(.*)*', component: NotFound }
总结对比
区别点 Vue 2 (Vue Router 3) Vue 3 (Vue Router 4)
创建方式 new VueRouter() createRouter()
模式配置 mode: 'history' history: createWebHistory()
组件内使用 this.router / this.route useRouter() / useRoute()
导航守卫 必须调用 next() next() 可选,推荐 return
404路由 path: '*' path: '/:pathMatch(.*)*'
总的来说,如果你正在从 Vue 2 迁移到 Vue 3,路由部分的改造是不可避免的,但 Vue 3 的新写法在 TypeScript 支持和逻辑复用性上都更加优秀。