在Vue3 Composition API中 附带了一个 setup() 方法。此方法封装了我们的大多数组件代码,并处理了响应式,生命周期钩子函数等。
Composition API使我们能够更好地将代码组织为更多的模块化功能,而不是根据属性的类型(方法,计算的数据)进行分离。
vue3的生命周期函数跟vue2.x版本有了很大的不同,在vue3中移除了beforeCreate 和 created,增加了setup函数.除了这2个之外还有9个生命周期函数
onBeforeMount onMounted onBeforeUpdate onUpdated onBeforeUnmount onUnmounted onActivated onDeactivated onErrorCaptured onRenderTracked // vue3新增加 onRenderTriggered // vue3新增加 命名上在vue2.x的基础上加上on前缀,以驼峰命名方式命名.
使用方法是直接导入,然后在setup函数里面直接调用
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onActivated, onDeactivated, onErrorCaptured } from "vue";
export default { setup() { onBeforeMount(() => { // ... }) onMounted(() => { // ... }) onBeforeUpdate(() => { // ... }) onUpdated(() => { // ... }) onBeforeUnmount(() => { // ... }) onUnmounted(() => { // ... }) onActivated(() => { // ... }) onDeactivated(() => { // ... }) onErrorCaptured(() => { // ... }) } }