探討父元件和兄弟元件的生命週期
當我們被問起vue的生命週期的時候,我們自然就回答到有beforeCreate,created,mounted,updated,destroy。就是一個生命的開始和結束。這次我們探討的是我們有兄弟元件的時候,各個元件在執行鉤子函式的時候的執行順序是怎麼樣的,按照之前的理解:是先執行完兄弟元件A的生命週期再執行兄弟元件B的生命週期。如果是這樣的話,那麼vue的執行效率是不高的。
什麼是父元件
之前自己本身一直有個誤區,在進行父子元件進行傳值的時候,我們經常會說,在父元件繫結一個值,子元件用prop接收。
<template> <div> <custom-child :value='value'></custom-child> </div> </template> 複製程式碼
一直以為<custom-child></custom-child>
這個就是父元件,因為官網也常說父元件繫結值,其實真正的父元件是
這個
<!--我才是父元件--> <div> <custom-child></custom-child> <div> 複製程式碼
<!-- 我才是子元件--> <custom-child></custom-child> 複製程式碼
ps:不知道有沒有人之前和我想的一樣
什麼是生命週期
你把一個元件想象為一個生命,有一個由生 (create) 到死 (destroy)的過程。這個過程可以分成很多階段,比如構造階段、更新階段、析構/銷燬階段,不同階段依據特定的順序和條件依次經歷。這就是元件的生命週期 (Life cycle)。
如果把不同階段實現為一個個函式的話,一個元件看起來就是這個樣子:
function component(){ create() update() destroy() } 複製程式碼
什麼是鉤子函式
你在定義這個「生命」的階段之外,還可以預留多個時機,好根據不同的場合執行不同的邏輯,就像這樣:
function component() { if (beforeCreate !== undefined) beforeCreate() create() if (afterCreate !== undefined) afterCreate() if (beforeUpdate !== undefined) beforeUpdate() update() if (afterUpdate !== undefined) afterUpdate() if (beforeDestroy !== undefined) beforeDestroy() destroy() if (afterDestroy !== undefined) afterDestroy() } 複製程式碼
這些 beforeXxx、afterXxx 就是鉤子(Hooks) ,它們連線了元件生命週期的不同階段,給你在元件預設行為之上執行自定義邏輯的機會。
父元件
<template> <div class="father"> <component-A class="son_A"></component-A> <component-B class="son_B"></component-B> </div> </template> export default{ beforeCreate() { console.group("%c%s", "color:black", "beforeCreate 建立前狀態-->>>>父元件"); }, created() { console.group("%c%s", "color:black", "created 建立完畢狀態-->>>>父元件"); }, beforeMount() { console.group("%c%s", "color:black", "beforeMount 掛載前狀態-->>>>父元件"); }, mounted() { console.group("%c%s", "color:black", "mounted 掛載完畢狀態-->>>>父元件"); }, beforeUpdate() { console.group("%c%s", "color:black", "beforeUpdate 更新前狀態-->>>>父元件"); }, updated() { console.group("%c%s", "color:black", "updated 更新後狀態-->>>>父元件"); }, beforeDestroy() { console.group("%c%s","color:black","beforeDestroy 元件銷燬前狀態-->>>>父元件"); }, destroyed() { console.group("%c%s","color:black","destroyed 元件銷燬後狀態-->>>>父元件"); } } 複製程式碼
子元件
子元件也依次按照這順序寫出來,就不依依展示了。