• Vue3 生命周期


    如下是Vue3的生命周期函数图: 

    一、Vue2生命周期和Vue3声明周期的区别

    1.  Vue2 中,只要创建Vue实例对象而不需要挂载就可以实现beforeCreate 和 created 生命周期函数。

    Vue3中必须要将Vue实例对象挂载完成,所有的准备工作做完,才可以开始实现beforeCreate 和 created 生命周期函数。

    2.  Vue2 我们销毁组件,触发的是beforeDestroy 和 destroyed 函数。

    在Vue3中,我们销毁组件变为了卸载组件,实现的功能是一致的,不过只是称呼变了,触发的生命周期函数为beforeUnmount 和 unmounted。

    二、Vue3生命周期的使用

    (一)以配置项的形式调用

    和Vue2中调用生命周期函数的方法一致,注意是与setup函数平级。

    如下生命周期函数有不懂的,可以参考这篇文章:

    Vue生命周期-CSDN博客

    1. export default {
    2. name: "MyItem",
    3. setup() {},
    4. beforeCreate() {
    5. console.log("beforeCreate生命周期函数");
    6. },
    7. created() {
    8. console.log("created生命周期函数");
    9. },
    10. beforeMount() {
    11. console.log("beforeMount生命周期函数");
    12. },
    13. mounted() {
    14. console.log("mounted生命周期函数");
    15. },
    16. beforeUpdate() {
    17. console.log("beforeUpdate生命周期函数");
    18. },
    19. updated() {
    20. console.log("update生命周期函数");
    21. },
    22. beforeUnmount() {
    23. console.log("beforeUnmount生命周期函数");
    24. },
    25. unmounted() {
    26. console.log("unmounted生命周期函数");
    27. },
    28. };

    (二)以composition API 形式调用

    以上的生命周期函数和composition API 对应形式如下:

    beforeCreate ----> setup()

    created ----> setup()

    beforeMount ----> onBeforeMount

    mounted ----> onMounted

    beforeUpdate ----> onBeforeUpdate

    updated ----> onUpdated

    beforeUnmount ----> onBeforeUnmount

    unmounted ----> onUnmounted

    使用以上composition API 之前需要先对要使用的API按需引入:

     import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from "vue";

    语法格式如下:

    API (() => {  // 内部执行内容  })

    1. import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from "vue";
    2. export default {
    3. name: "MyItem",
    4. setup() {
    5. onBeforeMount(() => {
    6. console.log("beforeMount生命周期函数");
    7. })
    8. onMounted(() => {
    9. console.log("mounted生命周期函数");
    10. })
    11. onBeforeUpdate(() => {
    12. console.log("beforeUpdate生命周期函数");
    13. })
    14. onUpdated(() => {
    15. console.log("update生命周期函数");
    16. })
    17. onBeforeUnmount(() => {
    18. console.log("beforeUnmount生命周期函数");
    19. })
    20. onMounted(() => {
    21. console.log("unmounted生命周期函数");
    22. })
    23. }
    24. };
  • 相关阅读:
    浅谈后置处理器之正则表达式提取器
    第一讲 react的基础---安装 特点 组件 生命周期
    详细给你讲明白JVM发生CMS GC的 5 种情况
    Dubbo-服务暴露
    基于STM32+物联网设计的货车重量检测系统(OneNet)
    oak深度相机入门教程-Gen2 相机
    QT 自定义QGraphicsItem 缩放后旋转 图形出现漂移问题
    项目架构:vue3 + vite + directive指令模块封装
    推荐十个优秀的ASP.NET Core第三方中间件,你用过几个?
    LoRA和QLoRA微调语言大模型:数百次实验后的见解
  • 原文地址:https://blog.csdn.net/XunLin233/article/details/134429991