Vue2.x升级到3

最主要的变化是在2的基础上加了个新的写法setup(){},新写法里没有熟悉的this,以及以前的一些写法都要改,要用2的写法也可以,用defineComponent()函数,vue3用TypeScript,用了3,相应配套的vuex、vue-router以及相关的组件库Vant3Element-plus都要升级起来,自然升级了有一堆的新语法要熟悉。

用2.X式写法

用全局API:defineComponent,就可以愉快的像2.0一样玩耍了
示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script lang="ts">
import {defineComponent} from 'vue';
export default defineComponent({
name: 'demo',
data() {
return {
demo: '',
};
},
computed: {},
watch: {},
methods: {},
created() {},
mounted() {},
});
</script>

新加的写法

新的组合式API,把原来生命周期式函数都拧到一个大函数里了;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script lang="ts">
import {ref, reactive, onMounted} from "vue";
import { useRoute } from "vue-router";

export default {
name: 'layout',
components:{},
setup() {
const data = reactive({demo:''});
const fn = ()=>{
// menus
}
return {
...data,
fn,
}
},
};
</script>

setup

生命周期

  • beforeCreate -> setup()
  • created -> setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured

ref

this

Mixin