使用vue2.7的背景
因为现有的h5项目要兼容老的安卓版本,我们想将vue2升级为vue3,但是vue3基于es6的proxy, 而proxy现在无法被babel-pollyfill转成es5,但是又想在项目中使用vue3的新语法,流畅使用ts,因此将目光转到使用vue2.7,
vue2.7是vue官方团队今年出的新版本,代号Naruto(看过火影的都知道这个是谁了吧), vue2.7兼容了vue3的许多写法,但是底层基于es5的Object.defineProperty实现,对vue3的新特性和ts支持都很友好,很完美符合我们的要求,那就来看看vue2.7和vue3在项目上具体有啥区别
vue2.7项目搭建注意
首先是package.json
直接使用vue-cli创建vue2的项目,然后再更改vue版本
"dependencies": {
"core-js": "^3.8.3",
"vue": "^2.7.10"
},
"devDependencies": {
"@babel/core": "^7.12.16",
"@babel/eslint-parser": "^7.12.16",
"@vue/cli-plugin-babel": "~5.0.0",
"@vue/cli-plugin-eslint": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"eslint": "^7.32.0",
"eslint-plugin-vue": "^8.0.3",
"vue-template-compiler": "^2.6.14"
},
上面这些依赖就是和vue2.7搭配的核心依赖,假如版本号过低或者过高有可能报错
对于main.js
import 'babel-polyfill';
import 'core-js/stable';
import 'regenerator-runtime/runtime';
import router from '@/router';
import Vue from 'vue';
import App from '@/App.vue';
Vue.config.productionTip = false;
new Vue({
router,
render: h => h(App),
}).$mount('#app');
main.js和vue2的写法保持一致,使用new Vue,而vue3中是使用createApp;
注意在vue2.7中使用babel-pollyfill时,需要在main.js中引入下面这三个库,同时在vue.config.js中加上 transpileDependencies: ['xxx'],其中xxx代表node_modules下的第一层目录名, cli.vuejs.org/zh/config/#…
import 'babel-polyfill';
import 'core-js/stable';
import 'regenerator-runtime/runtime';
对于vue-router的使用
在vue2.7中还是使用vue-router@3, 这点和vue3也是有区别(vue3使用vue-router@4)
"vue-router": "^3.6.5",
vue-router的使用和普通vue2项目中使用一致
在vue2.7中普通vue文件写法
普通vue文件和vue3中写法一致,使用ref或者reactive定义响应式变量,使用setup,同时return需要在html中使用的变量
<template>
<div>
<Loader :pageConfig="state.pageConfig"> </Loader>
</div>
</template>
<script>
import {reactive, getCurrentInstance, onMounted} from 'vue';
import hasIn from 'lodash/hasIn';
export default {
components: {
Loader,
},
setup() {
const state = reactive({
pageConfig: {},
events: {},
});
return {
state
}
}
}
这样一个vue3项目就可以改造成一个vue2.7项目啦