mpvue生命周期初探
最近使用了 mpvue 搭建并開發了公司一個小程序項目,周末花點時間研究一下 Vue.js 組件生命周期和小程序頁面生命周期的調用順序問題。
正文
準備知識
先上 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.json 的 pages 屬性中定義的所有頁面,并依次觸發每個頁面的 beforeCreate,created,而這對函數的執行先后,取決于頁面在 pages 屬性中的順序。
而小程序啟動一定需要打開一個首頁(這個首頁一定是在 pages 中第一個),這個頁面的 onLoad~mounted 是在最后一個頁面的 created 之后執行:
頁面之間跳轉(也叫路由切換)
頁面分: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 |
最后
onLaunch 和 onError 只存在于 App 實例中,其他頁面或組件替代 onLaunch 的是 onLoad,沒有 onError
Demo 源碼在此,后面找時間研究一下頁面內使用一般組件時,他們生命周期的關系以及異步數據處理的問題。
轉載于:https://juejin.im/post/5b49f07c5188251afa62c4b6
總結
以上是生活随笔為你收集整理的mpvue生命周期初探的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: new操作符到底干了什么?
- 下一篇: 阅读代码工具:Visual Studio