mpvue生命週期初探

zhCN_超發表於2019-03-04

最近使用了 mpvue 搭建並開發了公司一個小程式專案,週末花點時間研究一下 Vue.js 元件生命週期和小程式頁面生命週期的呼叫順序問題。

正文

準備知識

先上 mpvue 生命週期官方圖解:

mpvue生命週期初探

小程式只有一個 App 例項,對應 mpvue 專案的 App.vue 裡面的內容,全頁面共享,mpvue 為這個例項以及元件(元件包括:tabBar 頁普通頁一般元件)新增了 Vue.js 的一些生命週期方法。

當然這些生命週期並不是在 App 例項元件中都有。

頁面之間

APP 例項

它的生命週期永遠是最先執行的,順序為:beforeCreate,created,onLaunch,beforeMount,mounted,onShow(後面例子省略這部分內容)。

一個頁面

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.jsonpages 屬性中定義的所有頁面,並依次觸發每個頁面的 beforeCreate,created,而這對函式的執行先後,取決於頁面在 pages 屬性中的順序。

而小程式啟動一定需要開啟一個首頁(這個首頁一定是在 pages 中第一個),這個頁面的 onLoad~mounted 是在最後一個頁面的 created 之後執行:

mpvue生命週期初探

頁面之間跳轉(也叫路由切換)

頁面分:tabBar 頁普通頁,兩者之間跳轉有限制

  • navigateTo, redirectTo 只能開啟非 tabBar 頁面
  • switchTab 只能開啟 tabBar 頁面

表格內全部按順序觸發,- 開頭的表示第一次進入才觸發,+ 開頭表示再次進入才觸發,沒有符號的表示每次進入都觸發

1.open-type="navigate"
當前頁面 目標頁面 當前頁觸發 目標頁面觸發
普通頁 普通頁 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
2.open-type="redirect"
當前頁面 目標頁面 當前頁觸發 目標頁面觸發 說明
普通頁 普通頁 onUnload onLoad
onShow
onReady
beforeMount
+ beforeUpdate
mounted
普通頁 tabBar頁 不支援
tabBar頁 普通頁 onUnload onLoad
onShow
onReady
beforeMount
mounted
tabBar頁 tabBar頁 不支援
3.open-type="reLaunch"
當前頁面 目標頁面 當前頁觸發 目標頁面觸發
普通頁 普通頁 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,然後觸發當前頁的:

  • onLoad
  • onShow
  • onReady
  • beforeMount
  • beforeUpdate
  • mounted
4.open-type="navigateBack",需要配合 delta 屬性使用,它的表現同下面描述的左上角返回按鈕
  • delta 超過頁面棧數量,返回到第一個頁面
  • delta <= 0 時,返回上一個頁面
5.tabBar 點選切換
當前頁觸發 目標頁面觸發
onHide - onLoad
onShow
- onReady
- beforeMount
- mounted
6.左上角返回按鈕

這個按鈕只在普通頁中存在

當前頁觸發 目標頁面觸發
onUnload onShow

最後

onLaunchonError 只存在於 App 例項中,其他頁面或元件替代 onLaunch 的是 onLoad,沒有 onError

Demo 原始碼在此,後面找時間研究一下頁面內使用一般元件時,他們生命週期的關係以及非同步資料處理的問題。

相關文章