vue2和vue3的路由变化

Vue 3 和 Vue 2 的路由(Vue Router)有非常明显的变化。

最核心的区别在于版本不兼容:Vue 3 必须搭配 Vue Router 4.x 使用,而 Vue 2 使用的是 Vue Router 3.x。

Vue 3 的路由在设计上更现代化,全面拥抱了组合式 API(Composition API)和 TypeScript。以下是两者在实际开发中最主要的几个区别:

  1. 路由实例的创建方式不同

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: ...

})

  1. 组件内获取路由对象的方式不同(最常用)

在 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>

  1. 导航守卫中 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 表示通过

})

  1. 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 支持和逻辑复用性上都更加优秀。

相关推荐
禅思院1 小时前
AI对话前端从入门到崩溃:一个长对话引发的五层优化战争【引子】
前端·面试·架构
TrisighT1 小时前
Electron 鸿蒙 PC 上点外链唤醒应用,我试了 6 种写法只有 1 种能跑
前端·electron·harmonyos
天才熊猫君2 小时前
配置与数据分离:一种可视化搭建的属性编辑方案
前端·javascript
林希_Rachel_傻希希3 小时前
web性能之相关路径——AI总结
前端·javascript·面试
竹林8183 小时前
用 wagmi v2 踩坑两天,我终于搞懂了多链钱包切换在 DeFi 前端中的正确姿势
前端·javascript
用户2136610035723 小时前
Vue项目搜索功能与面包屑导航
前端·javascript
星栈3 小时前
LiveView 的实时通信,爽是爽,但 PubSub 和广播也最容易把自己绕晕
前端·前端框架·elixir
用户2930750976693 小时前
告别关键词匹配,拥抱向量语义 —— RAG 搜索从零到一
前端
独孤留白3 小时前
从C到Rust:告别 C 的"指针 + 长度"手动模式
前端·rust
掘金安东尼4 小时前
中小厂前端候选人简历面试拆解:从 HR 面、技术面到主管面的双赢提问法
前端·面试