面试:Vue.js嵌套组件生命周期执行顺序是什么?
2020-11-23 本文已影响0人
莫伊剑客
有组件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。