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

相关推荐
超哥--5 小时前
B站视频内容智能分析系统(九):React 前端与管理面板
前端·react.js·前端框架
Cutecat_8 小时前
视频字幕处理工具横向:提取模式 vs 编辑模式,该如何选择
android·前端·ios·语音识别
qq_422152578 小时前
PDF 加水印工具怎么选?2026 年文档版权保护方案对比
前端·pdf·github
kyriewen8 小时前
手写 Promise.all、race、any:不到 30 行代码,解决并发异步的所有姿势
前端·javascript·面试
brucelee1869 小时前
OpenClaw 浏览器控制(Chrome MCP)完整教程
前端·chrome
ct9789 小时前
React 状态管理方案深度对比
开发语言·前端·react
胡志辉的博客10 小时前
深入浅出理解浏览器事件循环:从一道输出题讲到 Chrome 源码
前端·javascript·chrome·chromium·event loop
代码不加糖10 小时前
js中不会冒泡的事件有哪些?
前端·javascript·vue.js
懂懂tty10 小时前
Vue2与Vue3之间API差异
前端·javascript·vue.js
AI焦点10 小时前
跨越协议鸿沟:Tool Use状态机从Anthropic到OpenAI兼容体系的适配要点
前端·人工智能