• 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. };
  • 相关阅读:
    编译libigl笔记
    Unraid 使用技巧集合
    SpringAMQP
    详解JDK8中新的日期时间工具类,真的很好用
    非谓语动词
    【Java开发】 Springboot集成Mybatis-Flex
    基于SpringBoot大学生心理健康咨询管理系统的分析与设计
    hadoop主要组建简写笔记
    SCA Sentinel 分布式系统的流量防控(二)
    如何看待中小企业实现数字化转型难的问题?_光点科技
  • 原文地址:https://blog.csdn.net/XunLin233/article/details/134429991