mpvue生命周期初探

4,990 阅读3分钟

最近使用了 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.jsonpages 属性中定义的所有页面,并依次触发每个页面的 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

最后

onLaunchonError 只存在于 App 实例中,其他页面或组件替代 onLaunch 的是 onLoad,没有 onError

Demo 源码在此,后面找时间研究一下页面内使用一般组件时,他们生命周期的关系以及异步数据处理的问题。