查看原文
其他

Vue.js嵌套组件生命周期执行顺序

Dunizb 前端全栈开发者 2022-07-09

点击上方“做工程师不做码农”,并“置顶公众号”

第一时间接收我的随机文章



此前一次面试被问到的问题,第一次还确实有点懵逼,特此记录下来。


有组件A,组件B,组件C,组件C是组件B的子组件,组件B又是组件A的子组件,那么直观的层级结构如下:


ComponentA

--ComponentB

----ComponentC


问:他们之间生命周期函数的调用顺序是什么?


下面的代码表示上述结构,全局注册了三个组件Comp、childrenA 和 childrenB。在 childrenA 中引用 childrenB,在 Comp 中 引用 childrenA。

Vue.component('comp', { template: '<div><children-a></children-a></div>', beforeCreate() { console.log('Comp beforeCreate') }, created() { console.log('Comp created') }, beforeMount() { console.log('Comp beforeMount') }, mounted() { console.log('Comp mounted') },})Vue.component('childrenA', { template: '<div><children-b></children-b></div>', beforeCreate() { console.log('--childrenA beforeCreate') }, created() { console.log('--childrenA created') }, beforeMount() { console.log('--childrenA beforeMount') }, mounted() { console.log('--childrenA mounted') },})Vue.component('childrenB', { template: '<div>{{text}}</div>', data() { return { text: 'childrenB' } }, beforeCreate() { console.log('----childrenB beforeCreate') }, created() { console.log('----childrenB created') }, beforeMount() { console.log('----childrenB beforeMount') }, mounted() { console.log('----childrenB mounted') },})new Vue({ el: '#app'})


输出结果如下:

Comp beforeCreate
Comp created
Comp beforeMount
--childrenA beforeCreate
--childrenA created
--childrenA beforeMount
----childrenB beforeCreate
----childrenB created
----childrenB beforeMount
----childrenB mounted
--childrenA mounted
Comp mounted


可以看到,先执行父级的beforeCreate、created 和 beforeMount,然后再去执行子组件的beforeCreate、created 和 beforeMount,如果子组件下面没有子组件了,就执行 mounted,然后再返回父级执行 mounted。


整个过程用图表示如下:



坚持原创、坚持干货。关注我的公众号,第一时间接收原创、干货文章。专注大前端技术。

点个在看少个 bug👇

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存