mpvue生命周期初探
最近使用了 mpvue 搭建并開發(fā)了公司一個小程序項(xiàng)目,周末花點(diǎn)時間研究一下 Vue.js 組件生命周期和小程序頁面生命周期的調(diào)用順序問題。
正文
準(zhǔn)備知識
先上 mpvue 生命周期官方圖解:
小程序只有一個 App 實(shí)例,對應(yīng) mpvue 項(xiàng)目的 App.vue 里面的內(nèi)容,全頁面共享,mpvue 為這個實(shí)例以及組件(組件包括:tabBar 頁、普通頁、一般組件)添加了 Vue.js 的一些生命周期方法。
當(dāng)然這些生命周期并不是在 App 實(shí)例 和組件中都有。
頁面之間
APP 實(shí)例
它的生命周期永遠(yuǎn)是最先執(zhí)行的,順序?yàn)?#xff1a;beforeCreate,created,onLaunch,beforeMount,mounted,onShow(后面例子省略這部分內(nèi)容)。
一個頁面
App.vue|--- Page0.vue(默認(rèn)打開頁面) 復(fù)制代碼Page0.vue 順序執(zhí)行:
- beforeCreate
- created
- onLoad
- onShow
- onReady
- beforeMount
- mounted
多個頁面
// app.json(注意順序) {pages: ['/pages/Page0/main','/pages/Page2/main','/pages/Page1/main',] }// 頁面結(jié)構(gòu) App.vue|--- Page0.vue(默認(rèn)頁面)|--- Page1.vue|--- Page2.vue 復(fù)制代碼小程序啟動會注冊 app.json 的 pages 屬性中定義的所有頁面,并依次觸發(fā)每個頁面的 beforeCreate,created,而這對函數(shù)的執(zhí)行先后,取決于頁面在 pages 屬性中的順序。
而小程序啟動一定需要打開一個首頁(這個首頁一定是在 pages 中第一個),這個頁面的 onLoad~mounted 是在最后一個頁面的 created 之后執(zhí)行:
頁面之間跳轉(zhuǎn)(也叫路由切換)
頁面分:tabBar 頁和普通頁,兩者之間跳轉(zhuǎn)有限制:
- navigateTo, redirectTo 只能打開非 tabBar 頁面
- switchTab 只能打開 tabBar 頁面
表格內(nèi)全部按順序觸發(fā),- 開頭的表示第一次進(jìn)入才觸發(fā),+ 開頭表示再次進(jìn)入才觸發(fā),沒有符號的表示每次進(jìn)入都觸發(fā)
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 當(dāng)前頁面,小程序框架以棧形式維護(hù)的頁面,會順序出棧并觸發(fā)頁面的 onUnload,然后觸發(fā)當(dāng)前頁的:
- onLoad
- onShow
- onReady
- beforeMount
- beforeUpdate
- mounted
4.open-type="navigateBack",需要配合 delta 屬性使用,它的表現(xiàn)同下面描述的左上角返回按鈕。
- delta 超過頁面棧數(shù)量,返回到第一個頁面
- delta <= 0 時,返回上一個頁面
5.tabBar 點(diǎn)擊切換
| onHide | - onLoad onShow - onReady - beforeMount - mounted |
6.左上角返回按鈕
這個按鈕只在普通頁中存在
| onUnload | onShow |
最后
onLaunch 和 onError 只存在于 App 實(shí)例中,其他頁面或組件替代 onLaunch 的是 onLoad,沒有 onError
Demo 源碼在此,后面找時間研究一下頁面內(nèi)使用一般組件時,他們生命周期的關(guān)系以及異步數(shù)據(jù)處理的問題。
轉(zhuǎn)載于:https://juejin.im/post/5b49f07c5188251afa62c4b6
總結(jié)
以上是生活随笔為你收集整理的mpvue生命周期初探的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: new操作符到底干了什么?
- 下一篇: 动手理解Vue导航守卫