记录一次从vue2到vue3的踩坑过程
vue3beta已经上线,最近刚好有一个项目可以让自己随便造,于是就打算使用vue3来造,在此记录下从vue2升级到vue3的一个过程,这里使用的是自己配置的webpack.
vue2到vue3中webpack的一些变化
vue2到vue3中webpack打包的配置也发生了一下一些变化(暂时发现):
- 不再需要vue-template-compiler ,在vue3中,
vue-template-compiler
被剔除了,不需要这个包,而它的替代品是@vue/compiler-sfc
- 在执行npm run dev的时候可能会出现
Can't find Python executable "python", you can set the PYTHON env variable
,这个时候只要运行以下代码即可npm install --global --production windows-build-tools
- 在webpack打包配置中,resolves路径也有变化
resolves: { alias: { "@": PATHS.entry, 'vuex': 'vuex/dist/vuex.esm-bundler', 'vue': '@vue/runtime-dom' } }
- vue-loader引入方式发生变化
const { VueLoaderPlugin } = require('vue-loader')
包的版本
vue升级到3之后,相对应的vuex
以及vue-router
的版本也需要进行更新,一下是我这次使用的包的版本,由于vue3的写法发生变化,很多UI库都不支持,目前只发现antd以及element-plus支持,其中element-plus只是名字进行了改变,其使用方法以及样式都和element一样,除了引入方面发生变化外其他没有任何变化,可以直接从2转成3
npm install --save vue@3.0.0-beta.15 vue-router@4.0.0-alpha.13 vuex@4.0.0-beta.2
写法以及引入的改变
在vue3中,初始页面创建的写法,vue的引入以及vuex和vue-router的写法与引入都发生了改变
import { createStore } from 'vuex';
const store = createStore({
state: {},
getters: {},
actions: {},
mutations: {}
})
export default store;
vue-router的变化
在之前的4之前的vue-router有两种mode,分别是hash
以及history
,分别通过hash模拟页面url以及html5的History Api来达到切换页面无需重新加载的功能,而在vue-router4中,这些都被以模块的形式实现,并将其分配到新的history
选项中.其中
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
const router = createRouter({
routes: [],
history: createWebHashHistory(),// hash模式
history: createWebHistory()// history模式
})
export default router;
vue的改变
import { createApp } from "vue";
import App from "./App.vue";
import router from "./Router/index.js";
import store from "./Store/index.js";
const app = createApp(App);
app.use(store);
app.use(router);
app.mount('#app');
至此,一个最简易的,从vue2迁移到vue3的项目就可以运行了.至于vue3中一些其他的变化后续继续记录.