目录

小程序生命周期-47-小程序生命周期-页面生命周期

目录

小程序生命周期 —— 47 小程序生命周期 - 页面生命周期

小程序的页面生命周期是指小程序页面从 加载 → 运行 → 销毁的整个过程;

页面生命周期函数需要在每个页面的 Page() 方法中进行定义;

https://i-blog.csdnimg.cn/direct/7aed3abe9022411298b99b365944cfd8.png#pic_center

下面我们分析一下页面生命周期函数的执行顺序和触发时机:

  • 访问页面,小程序会加载页面,触发 onLoad 函数;
  • 小程序在前台展示,执行 onShow 函数;
  • 当页面初次渲染完毕,代表页面已经准备妥当,可以和视图层进行交互,触发 onReady 函数;
  • 当用户浏览完当前页面后,需要跳转到其它页面;假如使用 navigate 组件进行跳转,属性值 open-type 设置为 redirect(redirect 代表关闭当前页面,跳转到下一个页面),会触发 onUnload 函数,用于监听页面卸载;如果 open-type 的属性值设置为 navigate (navigate 会保留当前页面。跳转到下一个页面),会触发 onHide 函数,隐藏当前页面,在下一个页面可以点击返回,返回到当前页面,这时候就会执行 onShow 函数;

页面生命周期函数中有两个函数需要特别注意:onLoad 函数和 onReady 函数,这两个函数在一个页面中只会调用一次;

下面我们打开微信开发者工具进行演示这几个生命周期函数的执行顺序和触发时机:

在 pages/cate/cate.js 中添加以下代码:

Page({

  /**
   * 页面的初始数据
   */
  data: {
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('onLoad 页面创建的时候执行')
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log('onReady 页面初次渲染完成,代表页面已经准备完毕,可以和视图层进行交互')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('onShow 页面在前台展示的时候')
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('onHide 页面隐藏')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('onUnload 页面卸载')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})

点击渲染,可以在 console 区域看到以下打印信息:

https://i-blog.csdnimg.cn/direct/85bccf7b40454d8dada50e83f3a58958.png#pic_center

接着在 pages/cate/cate.wxml 中添加页面跳转功能,演示一下其它生命周期函数的功能,如下:

<navigator url="/pages/list/list" open-type="redirect">跳转到列表页面</navigator>

点击页面的跳转,可以在 console 区域看到 onUnload 函数打印的信息,如下:

https://i-blog.csdnimg.cn/direct/75d72ed113fb454ea1fa68cc4699007c.png#pic_center

修改一下 open-type 的属性值,如下:

<navigator url="/pages/list/list" open-type="redirect">跳转到列表页面-redirect</navigator>
<navigator url="/pages/list/list" open-type="navigate">跳转到列表页面-navigate</navigator>

点击页面中的 navigate 属性的跳转,可以在 console 区域看到执行的是 onHide 生命周期函数,如下:

https://i-blog.csdnimg.cn/direct/93e3d4b8b0494f1298338ca417d1991c.png#pic_center

在 navigate 模式下可以点击返回箭头,返回到上一个页面,在 console 区域中可以看到,点击返回上一个页面后,会触发 onShow 生命周期函数,如下:

https://i-blog.csdnimg.cn/direct/3c0ff564d2c548fe997edeb78fd03fdb.png#pic_center

当前页面在切换到后台时,也会触发 onHide 生命周期函数,当我们点击页面右上角的关闭按钮时,可以在 console 区域看到 onHide 生命周期函数被触发,如下所示:

https://i-blog.csdnimg.cn/direct/2f6f73314c3d4ad2879030aeaa42b3fc.png#pic_center

从后台切换到前台时,会触发 onShow 生命周期函数,如下所示:

https://i-blog.csdnimg.cn/direct/bc2e6919d57a4473a4ab8fe940f041b7.png#pic_center

参考视频: