«

Vue2和Vue3生命周期变化

时间:2023-7-27 01:18     作者:六思逸     分类: Vue


前面vue2(选项式) 后面vue3(组合式)

beforeCreate -> setup() 开始创建组件之前,创建的是data和method
created -> setup()

beforeMount -> onBeforeMount 组件挂载到节点上之前执行的函数
mounted -> onMounted 组件挂载完成后执行的函数

beforeUpdate -> onBeforeUpdate 组件更新之前执行的函数
updated -> onUpdated 组件更新完成之后执行的函数

beforeDestroy -> onBeforeUnmount 组件挂载到节点上之前执行的函数
destroyed -> onUnmounted 组件卸载之前执行的函数

在vue3中的setup选项api中还是可以使用vue2的生命周期如:

export default {
  beforeCreate() {
    console.log("我是beforeCreate");
  },
  created() {
    console.log("我是created");
  },
  beforeMount() {
    console.log("我是beforeMount");
  },
  mounted() {
    console.log("我是mounted");
  },
  setup() {
    console.log("我是setup");
    onBeforeMount(() => {
      console.log("我是onBeforeMount");
    });
    onMounted(() => {
      console.log("我是onMounted");
    });
  },
};

在vue3.0中还是可以直接使用的,结果如下:

首先因为vue3.0中将选项api如:data,methods,等全部变成了setup组合api包括vue2.x中的生命周期,且在vue3.0setup执行优先级要比vue2.x中的生命周期要高,所以不推荐在vue3.0中使用vue2.x的生命周期钩子,在vue3.0使用生命周期钩子,需要先引入再使用:

import { onMounted, onBeforeMount } from "vue";
且是在setup组合api中以函数的形式写入:

  setup() {
    console.log("我是setup");
    onBeforeMount(() => {
      console.log("我是onBeforeMount");
    });
    onMounted(() => {
      console.log("我是onMounted");
    });
  },

标签: 生命周期 Vue3 Vue2和Vue3生命周期变化

版权所有:六思逸
文章标题:Vue2和Vue3生命周期变化
除非注明,文章均为 六思逸 原创,转载请注明作者和出处 六思逸

扫描二维码,在手机上阅读

推荐阅读: