Vue嵌套組件的生命週期

嵌套組件的生命週期

問:有A、B、C三個組件,A爲B的父組件,B爲C的父組件,它們的建立和掛載順序是怎樣的?即(beforeCreate/created,beforeMounte/mounted)的執行順序。javascript

話很少說,直接上代碼:html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <title>嵌套組件的生命週期</title>
</head>
<body>
    <div id="app">
        <component-a />
    </div>   

    <script> Vue.component('component-a', { template: '<div><component-b></component-b></div>', beforeCreate () { console.log('beforeCreate: A'); }, created() { console.log('created: A'); }, beforeMount() { console.log('beforeMount: A'); }, mounted() { console.log('mounted: A'); }, }); Vue.component('component-b', { template: '<p><component-c></component-c></p>', beforeCreate () { console.log('beforeCreate: B'); }, created() { console.log('created: B'); }, beforeMount() { console.log('beforeMount: B'); }, mounted() { console.log('mounted: B'); }, }); Vue.component('component-c', { template: '<span>hello world</span>', beforeCreate () { console.log('beforeCreate: C'); }, created() { console.log('created: C'); }, beforeMount() { console.log('beforeMount: C'); }, mounted() { console.log('mounted: C'); }, }); const app = new Vue({ el: '#app', beforeCreate () { console.log('beforeCreate: Root'); }, created() { console.log('created: Root'); }, beforeMount() { console.log('beforeMount: Root'); }, mounted() { console.log('mounted: Root'); } }); </script>
</body>
</html>
複製代碼

直接看打印結果:vue

beforeCreate: Root
created: Root
beforeMount: Root
beforeCreate: A
created: A
beforeMount: A
beforeCreate: B
created: B
beforeMount: B
beforeCreate: C
created: C
beforeMount: C
mounted: C
mounted: B
mounted: A
mounted: Root
複製代碼

經過打印結果咱們能夠看到,beforeCreate、created、beforeMounted是按順序執行,由外到內;而mounted即最終的掛載階段則是由內到外,先將子組件掛載到dom上,而後再是父組件。java

爲何

其實想一想就知道了,既然組件之間存在父子關係,即父嵌套子,那麼子組件就至關於父組件的一部分,那確定要先將其一部分先掛載到dom上,而後再將整個父組件掛載上去。git

總結

父子組件嵌套的生命週期其實都是 先父後子 而後 先子後父。後續再加入update和destroy的相關代碼。github

github連接:user-gold-cdn.xitu.io/2019/3/7/16…,歡迎👏👏👏starnpm

相關文章
相關標籤/搜索