「Vue component生命週期」相關筆記
原始問題
Vue component 從建立到摧毀,會經過數個階段的生命週期;請描述以下這兩個 DOM 元素的生命週期發生順序為何?
<header>
<nav></nav>
</header>
回答
- 先是
header的 beforeCreate、created 與 beforeMount(header準備掛載) - 接著
nav進行 beforeCreate、created 與 beforeMount(nav準備掛載) navmounted,然後headermounted(掛載nav後,掛載header)- 準備銷毀時先
headerbeforeDestroy,接著navbeforeDestroy(header準備銷毀,接著nav準備銷毀) navdestroyed,最後headerdestroyed(銷毀nav後再銷毀header)
遇到資料更新時則是beforeUpdate接updated
自作純觀察用的奈米專案(結果輸出於 devTool console):demo | repo

版本與環境
vue: 2.6.11
筆記
- 透過
console.log可觀察到this.$data在created後才可取用(操作)- Vue.js 技術揭密:可以從原始碼看到
beforeCreate和created的 hook 分別在initState的前後調用,而initState的作用是初始化props、data、methods、watch、computed等屬性,所以在beforeCreate的 hook 無法取用 props、data 定義的值,也不能調用methods中的 function。
- Vue.js 技術揭密:可以從原始碼看到
$el與$ref皆是mounted後才可取用- 重新認識 Vue.js:直到
mounted階段,Vue 才正式將網頁上的 DOM 節點、事件都綁定至 Vue 的實體。也就是說,如果我們基於某些原因需要手動操作 DOM API,如querySelector或addEventListener等,最好在mounted階段完成後進行操作,以免操作的 DOM 節點被 Vue 替換掉。 - functions in
mountedhook: called after the instance has been mounted, whereelis replaced by the newly createdvm.$el. - An important note about the
refregistration 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!
- 重新認識 Vue.js:直到
- 在
beforeUpdate階段時,資料就已經更新了,只是還未重渲染畫面;updated則代表「畫面已更新」- Vue 的
$nextTick()就是要確保其cb()在畫面更新後才執行
- Vue 的
- Vue component 被銷毀(
destroyed)後,無法再透過 Vue 操作 DOM($ref的值變為undefined)(devTool 中的 Vue extension 也不再顯示相關內容),但 DOM 元素依舊存在