likes
comments
collection
share

vue-cli4.x+vue2.6升级vue2.7 实录

作者站长头像
站长
· 阅读数 9

动机

在工作中,因业务开发的压力没有时间升级vue3.x,确想使用vue3.x的组合式 API (Composition API),至于组合式API这里就不展开讲了,可自行查看官方文档

vue2.7则提供了内置的组合式API支持,因此这就涉及到在现在的项目基础上升级到vue2.7过程,官方迁移文档

升级步骤

1. 升级本地 @vue/cli-xxx 相关依赖版本至 ~4.5.18

// 升级前
// "@vue/cli-plugin-babel": "~4.5.0",
// "@vue/cli-plugin-eslint": "~4.5.0",
// "@vue/cli-plugin-router": "~4.5.0",
// "@vue/cli-plugin-vuex": "~4.5.0",
// "@vue/cli-service": "~4.5.0",

// 升级后
"@vue/cli-plugin-babel": "~4.5.18",
"@vue/cli-plugin-eslint": "~4.5.18",
"@vue/cli-plugin-router": "~4.5.18",
"@vue/cli-plugin-vuex": "~4.5.18",
"@vue/cli-service": "~4.5.18",

2. 将 vue 升级至 ^2.7.0

// 升级前
// "vue": "^2.6.11",

// 升级后
"vue": "^2.7.0",

3. 移除 vue-template-compiler 依赖

4. 安装 vue-loader 依赖

"vue-loader": "^15.10.0"

否则会出现下列的报错

vue-cli4.x+vue2.6升级vue2.7 实录

5. 升级

// 升级前
"eslint-plugin-vue": "^6.2.2",

// 升级后
"eslint-plugin-vue": "^9.0.0",

注意事项

1. 不能移除 package-lock.json 来重新安装依赖,否则会出现下列报错

vue-cli4.x+vue2.6升级vue2.7 实录

vue-cli4.x+vue2.6升级vue2.7 实录

使用过程的问题

1. 如何在 vue-router@3.x 版本中定义组件内导航守卫

(1)使用 defineComponent 方法

<script>
import { defineComponent } from "vue";

export default defineComponent({
  beforeRouteEnter: (to, from, next) => {
    // do somethings...
  }
});
</script>

<script setup>
// do somethings...
</script>

(2)使用 unplugin-vue-define-options

unplugin-vue-define-options 官方文档

安装

npm i unplugin-vue-define-options -D

使用

vue.config.js中添加插件

module.export = {
  configureWebpack(config) {
    config.plugins.push(require("unplugin-vue-define-options/webpack")())
  }
}
<script>
import { defineComponent } from "vue";

defineOptions({
  beforeRouteEnter(to, from, next) {
    // do somethings...
  }
});
</script>