Vue父子组件的生命周期执行顺序


前言

提示:这里可以添加本文要记录的大概内容:

本文主要介绍了Vue父子组件的生命周期执行顺序,并且简单介绍了生命周期的概念


提示:以下是本篇文章正文内容,下面案例可供参考

一、什么是生命周期

从Vue实例从创建、运行到销毁期间,总是伴随着各种各样的事件,这些事件统称为生命周期。
伴随vue的创建、运行到销毁,有八个重要的生命周期钩子函数,分别是
beforeCreate() 初始化之前执行
created() 初始化之后
beforeMount() 挂载到页面之前
mounted() 渲染到页面之后
beforeUpdate() 数据更新前
updated() 数据更新后
beforeDestroy() vue销毁前
destroyed()vue销毁后
在这里插入图片描述

二、执行顺序

1. 分别在父组件和子组件都打印生命周期

//父组件中在每个生命周期函数里都打印函数名字
 	beforeCreate() {
        console.log('beforeCreate')
    },
    created() {
        console.log('created')
    },
    beforeMount() {
        console.log('beforeMount')
    },
    mounted() {
        console.log('mounted')
    },
    beforeUpdate() {
        console.log('beforeUpdate')
    },
    updated() {
        console.log('updated')
    },
    beforeDestroy() {
        console.log('beforeDestroy')
    },
    destroyed() {
        console.log('destroyed')
    }
// 子组件中在每个生命周期函数里都打印函数名字----SON
 beforeCreate() {
        console.log('beforeCreate----SON')
    },
    created() {
        console.log('created----SON')
    },
    beforeMount() {
        console.log('beforeMount----SON')
    },
    mounted() {
        console.log('mounted----SON')
    },
    beforeUpdate() {
        console.log('beforeUpdate----SON')
    },
    updated() {
        console.log('updated----SON')
    },
    beforeDestroy() {
        console.log('beforeDestroy----SON')
    },
    destroyed() {
        console.log('destroyed----SON')
    }

2. 控制台中打印结果如下

在这里插入图片描述

3. 父子组件的生命周期执行顺序

可以看到父组件在渲染完成之后并不是马上挂载,而是先等待子组件创建、渲染、挂载完成之后再去挂载。

创建实例是从外到内的,渲染是从内到外的

(1)加载渲染过程:

父beforeCreate —> 父created —> 父beforeMount —> 子beforeCreate —> 子created —> 子beforeMount —> 子mounted —> 父mounted

(2)更新过程:

子组件中数据改变时:

父组件 beforeUpdate -> 子组件 beforeUpdate -> 子组件 updated -> 父组件 updated
在这里插入图片描述

父组件中数据改变时:

父组件 beforeUpdate -> 父组件 updated在这里插入图片描述

(3)销毁过程:

父组件 beforeDestroy -> 子组件 beforeDestroy -> 子组件 destroyed -> 父组件 destroyed


总结

加载渲染阶段:
在这里插入图片描述
更新阶段:在这里插入图片描述
销毁阶段:在这里插入图片描述

  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值