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

相关推荐
葡萄城技术团队3 小时前
一键触发工作表中所有异步函数:用依赖单元格刷新 SpreadJS 公式
前端
天道kabuto3 小时前
踩坑复盘:为什么在输入框按个回车,页面就偷偷刷新了?
vue.js
Bigger3 小时前
谁动了我的 URL?——记一次微前端"灵异 Bug"的排查实录
前端·ai编程·vue-router
JavaGuide3 小时前
轻量开源版 IDEA 来了!
前端·后端
张洪权3 小时前
nest.js websocket 群聊----私聊功能
前端·nestjs
流光D3 小时前
AI Era: Building Web Sites and Configuring Nginx Reverse Proxy Process
前端·人工智能·nginx
sakidd3 小时前
VS Code 的 AI Chat 现在已经这么能干了?
前端
吴长建先生3 小时前
Vue.js支付回调页面如何设计才能保障对账准确性?
vue.js
计算机魔术师4 小时前
英伟达砸130亿美元买下一个平台,黄仁勋到底在怕什么?
前端
leoZ2314 小时前
第 2 篇:搭建地基——Vue3 + Vite + Tailwind v4 + shadcn-vue
前端·javascript·vue.js·人工智能·目标检测·数据挖掘·语音识别