最近使用了 mpvue 搭建並開發了公司一個小程序項目,週末花點時間研究一下 Vue.js 組件生命週期和小程序頁面生命週期的調用順序問題。html
先上 mpvue 生命週期官方圖解: vue
小程序只有一個 App 實例
,對應 mpvue 項目的 App.vue
裏面的內容,全頁面共享,mpvue 爲這個實例以及組件
(組件包括:tabBar 頁
、普通頁
、通常組件
)添加了 Vue.js 的一些生命週期方法。git
固然這些生命週期並非在 App 實例
和組件
中都有。github
它的生命週期永遠是最早執行的,順序爲:beforeCreate
,created
,onLaunch
,beforeMount
,mounted
,onShow
(後面例子省略這部份內容)。json
App.vue
|--- Page0.vue(默認打開頁面)
複製代碼
Page0.vue
順序執行:小程序
beforeCreate
created
onLoad
onShow
onReady
beforeMount
mounted
// app.json(注意順序)
{
pages: [
'/pages/Page0/main',
'/pages/Page2/main',
'/pages/Page1/main',
]
}
// 頁面結構
App.vue
|--- Page0.vue(默認頁面)
|--- Page1.vue
|--- Page2.vue
複製代碼
小程序啓動會註冊 app.json
的 pages
屬性中定義的全部頁面,並依次觸發每一個頁面的 beforeCreate
,created
,而這對函數
的執行前後,取決於頁面在 pages
屬性中的順序。bash
而小程序啓動必定須要打開一個首頁(這個首頁必定是在 pages
中第一個),這個頁面的 onLoad
~mounted
是在最後一個頁面的 created
以後執行:app
頁面分:tabBar 頁
和普通頁
,二者之間跳轉有限制:框架
表格內所有按順序觸發,
-
開頭的表示第一次進入才觸發,+
開頭表示再次進入才觸發,沒有符號的表示每次進入都觸發異步
當前頁面 | 目標頁面 | 當前頁觸發 | 目標頁面觸發 |
---|---|---|---|
普通頁 | 普通頁 | onHide | onLoad onShow onReady beforeMount + beforeUpdate mounted |
普通頁 | tabBar頁 | onUnload | - onLoad onShow - onReady - beforeMount - mounted |
tabBar頁 | 普通頁 | onHide | onLoad onShow onReady beforeMount + beforeUpdate mounted |
tabBar頁 | tabBar頁 | onHide | - onLoad onShow - onReady - beforeMount - mounted |
當前頁面 | 目標頁面 | 當前頁觸發 | 目標頁面觸發 | 說明 |
---|---|---|---|---|
普通頁 | 普通頁 | onUnload | onLoad onShow onReady beforeMount + beforeUpdate mounted |
|
普通頁 | tabBar頁 | 不支持 | ||
tabBar頁 | 普通頁 | onUnload | onLoad onShow onReady beforeMount mounted |
|
tabBar頁 | tabBar頁 | 不支持 |
當前頁面 | 目標頁面 | 當前頁觸發 | 目標頁面觸發 |
---|---|---|---|
普通頁 | 普通頁 | onUnload | onLoad onShow onReady beforeMount + beforeUpdate mounted |
普通頁 | tabBar頁 | onUnload | + onUnload onLoad onShow onReady beforeMount + beforeUpdate mounted |
tabBar頁 | 普通頁 | onUnload | onLoad onShow onReady beforeMount + beforeUpdate mounted |
tabBar頁 | tabBar頁 | onUnload | onLoad onShow onReady beforeMount + beforeUpdate mounted |
若是 reLaunch 當前頁面,小程序框架以棧形式維護的頁面,會順序出棧並觸發頁面的 onUnload,而後觸發當前頁的:
delta
屬性使用,它的表現同下面描述的左上角返回按鈕。頁面棧
數量,返回到第一個頁面當前頁觸發 | 目標頁面觸發 |
---|---|
onHide | - onLoad onShow - onReady - beforeMount - mounted |
這個按鈕只在普通頁
中存在
當前頁觸發 | 目標頁面觸發 |
---|---|
onUnload | onShow |
onLaunch
和onError
只存在於App 實例
中,其餘頁面或組件替代onLaunch
的是onLoad
,沒有onError
Demo 源碼在此,後面找時間研究一下頁面內使用通常組件時,他們生命週期的關係以及異步數據處理的問題。