普通文組 2.5

「Vue component生命週期」相關筆記

原始問題

Vue component 從建立到摧毀,會經過數個階段的生命週期;請描述以下這兩個 DOM 元素的生命週期發生順序為何?

<header>
  <nav></nav>
</header>

回答

  1. 先是header的 beforeCreate、created 與 beforeMount(header準備掛載)
  2. 接著nav進行 beforeCreate、created 與 beforeMount(nav準備掛載)
  3. nav mounted,然後header mounted(掛載nav後,掛載header
  4. 準備銷毀時先header beforeDestroy,接著nav beforeDestroy(header準備銷毀,接著nav準備銷毀)
  5. nav destroyed,最後header destroyed(銷毀nav後再銷毀header

遇到資料更新時則是beforeUpdateupdated 自作純觀察用的奈米專案(結果輸出於 devTool console):demo | repo

vue component life cycle

版本與環境

vue: 2.6.11

筆記

  • 透過console.log可觀察到this.$datacreated後才可取用(操作)
    • Vue.js 技術揭密:可以從原始碼看到beforeCreatecreated的 hook 分別在initState的前後調用,而initState的作用是初始化propsdatamethodswatchcomputed等屬性,所以在beforeCreate的 hook 無法取用 props、data 定義的值,也不能調用methods中的 function。
  • $el$ref皆是mounted後才可取用
    • 重新認識 Vue.js:直到mounted階段,Vue 才正式將網頁上的 DOM 節點、事件都綁定至 Vue 的實體。也就是說,如果我們基於某些原因需要手動操作 DOM API,如querySelectoraddEventListener等,最好在mounted階段完成後進行操作,以免操作的 DOM 節點被 Vue 替換掉。
    • functions in mounted hook: called after the instance has been mounted, where el is replaced by the newly created vm.$el.
    • An important note about the ref registration timing: because the refs themselves are created as a result of the render function, you cannot access them on the initial render - they don’t exist yet!
  • beforeUpdate階段時,資料就已經更新了,只是還未重渲染畫面;updated則代表「畫面已更新」
    • Vue 的$nextTick()就是要確保其cb()在畫面更新後才執行
  • Vue component 被銷毀(destroyed)後,無法再透過 Vue 操作 DOM($ref的值變為undefined)(devTool 中的 Vue extension 也不再顯示相關內容),但 DOM 元素依舊存在

參考文件