最近使用了 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 源码在此,后面找时间研究一下页面内使用通常组件时,他们生命周期的关系以及异步数据处理的问题。