v2升级v3需要兼顾的几个方面

312 阅读3分钟

一、核心依赖升级

  1. 框架与工具链

    • Vue 核心库‌:

      npm uninstall vue && npm install vue@3.4.1  # 强制升级到最新稳定版‌
      
    • 配套库升级‌:

      npm install vue-router@4.3.2 vuex@4.1.3 @vue/test-utils@2.4.5  # 同步升级‌
      
  2. 构建工具迁移(Webpack → Vite)

    • 配置重构‌:替换 vue.config.js 为 vite.config.js,需显式声明路径别名和全局变量:

      import { defineConfig } from 'vite'
      export default defineConfig({
        resolve: { alias: { '@': '/src' } },
        define: { 'process.env': import.meta.env }  // 兼容旧环境变量写法‌
      })
      
    • 静态资源处理‌:

      // 旧写法(Webpack)
      const img = require('@/assets/logo.png')
      // 新写法(Vite)
      const img = new URL('./assets/logo.png', import.meta.url).href

二、代码层重构

  1. 组件定义变更

    • 组合式 API 替换‌:

      <!-- Vue 2(选项式) -->
      <script>
      export default {
        data() { return { count: 0 } },
        methods: { increment() { this.count++ } }
      }
      </script>
      
      <!-- Vue 3(组合式) -->
      <script setup>
      import { ref } from 'vue'
      const count = ref(0)
      const increment = () => count.value++‌
      </script>
      
  2. 生命周期钩子重命名

    Vue 2Vue 3触发场景
    beforeDestroybeforeUnmount组件销毁前清理定时器/事件监听‌
    destroyedunmounted组件已销毁后执行操作‌
  3. 全局 API 变更

    • Vue.prototype 替代‌:

      // Vue 2
      Vue.prototype.$http = axios
      
      // Vue 3
      const app = createApp(App)
      app.config.globalProperties.$http = axios‌
      
    • 过滤器(Filter)移除‌:

      vueCopy Code
      <!-- 旧写法 -->
      <div>{{ price | currency }}</div>
      <!-- 新写法 -->
      <div>{{ formatCurrency(price) }}</div>

三、生态兼容性问题

  1. UI 库迁移(Element UI → Element Plus)

    • 按需引入配置‌:

      // vite.config.js
      import Components from 'unplugin-vue-components/vite'
      import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
      export default defineConfig({
        plugins: [Components({ resolvers: [ElementPlusResolver()] })]
      })‌
      
  2. 路由系统升级(Vue Router v3 → v4)

    • 路由模式声明‌:

      // Vue 2
      new Router({ mode: 'history' })
      
      // Vue 3
      createRouter({ history: createWebHistory() })‌
      
    • 路由守卫参数变化‌:

      // Vue 2
      router.beforeEach((to, from, next) => { ... })
      
      // Vue 3
      router.beforeEach((to, from) => { ... })  // 移除 `next` 参数‌
      
  3. 状态管理(Vuex v3 → v4)

    • 模块注册变更‌:

      // Vue 2
      new Vuex.Store({ modules: { user } })
      
      // Vue 3
      createStore({ modules: { user } })‌
      

四、高频问题与解决方案

问题分类具体问题解决方案
模板语法v-model 默认绑定属性变为 modelValue显式声明绑定属性:<Child v-model:title="value" />,子组件通过 props.title 和 emit('update:title')
事件总线Vue 3 移除 $on/$off使用 mitt 库替代:emitter.on('event', callback)
响应式系统Proxy 导致数组索引修改未触发更新使用 Vue.set 或替换整个数组:list.value = [...newList]
TypeScriptthis 类型推断失败使用 defineComponent 包裹组件,并显式声明类型:export default defineComponent({ ... })
第三方插件vue-awesome-swiper 未适配 Vue 3替换为 swiper/vue 或 @vueuse/core 的 useSwiper

五、渐进式迁移策略

  1. 混合模式过渡

    • 兼容构建‌:通过 @vue/compat 允许新旧代码共存:

      // vite.config.js
      import vue from '@vitejs/plugin-vue'
      export default defineConfig({
        plugins: [vue({ template: { compatConfig: { MODE: 2 } } })]
      })‌
      
  2. 分模块升级优先级

    优先级模块类型示例
    1工具函数/工具类日期格式化、请求封装
    2基础组件Button、Input 等无状态组件
    3业务页面订单页、用户详情页等复杂逻辑页面‌
  3. 自动化检测工具

    • ESLint 规则‌:安装 eslint-plugin-vue 检测废弃 API‌
    • 迁移助手‌:运行 vue-migration-helper 扫描代码库‌

六、迁移后验证

  1. 功能测试

    • 核心场景‌:表单提交、路由跳转、状态管理、异步请求
    • 边界案例‌:大数据量列表渲染、SSR 兼容性、IE 降级方案(如有)‌
  2. 性能监控

    • 关键指标‌:首屏加载时间(FCP)、JS 包体积、内存泄漏检测
    • 优化建议‌:使用 vite-plugin-compression 压缩资源‌