Vue3和Vue2的生命周期差异

Vue组件实例在创建时要经历一系列的初始化步骤,在此过程中Vue会在合适的时机,调用特定的函数,从而会让开发者有机会在特定阶段运行自己的代码,这些特定的函数通称为:生命周期钩子

Vue2的生命周期

<template>
    <div></div>
</template>

<script>
    export default{
        data(){
            return {
            
            }
        },
        beforeCreate() {
            console.log('组件即将创建');
         },
        created() {
            console.log('组件已创建');
         },
        beforeMount() {
            console.log('组件挂载前');
         },
        mounted() {
            console.log('组件已挂载');
         },
        beforeUpdate() {
            console.log('组件更新前');
        },
        updated() {
            console.log('组件已更新');
        },
        beforeDestroy() {
            console.log('组件销毁前');
        },
        destroyed() {
            console.log('组件已销毁');
        }
       }
</script>

执行顺序依次为:

beforeCreate > created  > beforeMount > mounted > beforeUpdate > updated > beforeDestroy > destroyed

当有父子组件时执行顺序

1、父 beforeCreate‌ > 父 created

2、父 beforeMount‌ > 子 beforeCreate > 子 created > 子 beforeMount > 子 mounted > 父 mounted

3、当父组件的某些数据更新时

        父 beforeUpdate‌ > 子 beforeUpdate > 子 updated > 父 updated

4、当父组件销毁时

        父 beforeDestroy‌ > 子 beforeDestroy > 子 destroyed > 父 destroyed

Vue3的生命周期

<template>
    <div></div>
    <div></div>
</template>

<script setup >
    import { 
        onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnMount,onUnMounted 
    } from 'vue'

    onBeforeMount(()=>{
        //挂载前
    })

    onMounted(()=>{
        //挂载完毕
    })

    onBeforeUpdate(()=>{
        //更新前
    })

    onUpdated(()=>{
        //更新完毕
    })

    onBeforeUnMount(()=>{
        //卸载前
    })

    onUnMounted(()=>{
        //卸载完毕
    })
</script>

首次加载

父 setup → 父 onBeforeMount → 子 setup → 子 onBeforeMount → 子 onMounted → 父 onMounted

更新

父 onBeforeUpdate → 子 onBeforeUpdate → 子 onUpdated → 父 onUpdated

卸载

父 onBeforeUnmount → 子 onBeforeUnmount → 子 onUnmounted → 父 onUnmounted

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值