終於踏入Javascript框架之Vue..(9)LifeCycle

vue實例另一個比較重要也是會被問到的就是生命週期

在不同階段會自動調用

vue2.x跟vue3的差異

vue2.x vue3(composition API)
beforeCreate     setup
createdsetup
beforeMount onBeforemount
mountedonMounted
beforeUpdateonbeforeUpdate
updatedOnupdated
beforeDestroyOnbeforeDestroy
beforeUnmountOnbeforeUnmount

composition API中,setup取代created這個週期,其他大概是名稱一點點不同

  • 生命週期函數包括:
    • 創建:beforeCreate(--app.mount()創建實例--)Created(--computed, method,watcher監聽器都已配置好--),HTML尚未被渲染,因此還沒有生成DOM
    • 掛載:beforeMount(--render--)Mounted,在這邊可以找到DOM節點
    • 更新:whendatachange->>beforeUpdate(--reRender--)Updated
    • 銷毀:beforeUnmount(--移除應用--)Mounted
 
  • 在實際頁面運行的優先順序:渲染頁面>獲取數據
  • 父子組件的生命週期

父組件是在 created() 階段後加載完子組件,並在子組件 mounted() 後,父組件最後才 mounted()。


Parent:beforeCreate >
Parent:created >
Parent:beforeMount>

Child:beforeCreate >
Child:created >
Child:beforeMount>
Child:Mounted>

Parent:Mounted>

用一個比較簡單的例子來想,當我們設置一個按鈕將parent數據傳遞給child時,child必須要有個default值才不會報錯,所以child的創建會在parent之前。

ref:

https://medium.com/@seed45699/vue-%E9%9D%9E%E5%90%8C%E6%AD%A5%E8%99%95%E7%90%86%E5%92%8C%E7%88%B6%E5%AD%90%E7%B5%84%E4%BB%B6%E7%94%9F%E5%91%BD%E9%80%B1%E6%9C%9F%E4%B9%8B%E9%97%9C%E4%BF%82-5bd5fea513c6

 

https://ithelp.ithome.com.tw/m/articles/10275141

 

Comments