微信小程序之生命周期

1. 整个小程序生命周期 App({})

//app.js
App({
    onLaunch: function (options) {
        // 小程序初始化完成时(全局只触发一次) 
        // 程序销毁(过一段时间没有执行,或者手动删除了小程序后再次添加)之后,再次启动就会执行
        console.log('onLaunch'); 
    },
    onShow: function (options) {
        // 小程序启动,或从后台进入前台显示时
        console.log('onShow');
    },
    onHide: function () {
        // 小程序从前台进入后台时,就会执行
        console.log('onHide');
    },
    onError: function (msg) {
        // 小程序发生脚本错误,或者 api 调用失败时触发,会带上错误信息
        console.log(msg)
    },
    globalData: {
        userInfo: null
    }
})

2. 页面生命周期 page({})

Page({ 

  onLoad: function (options) {
    // 监听页面加载
    // 页面加载的时候执行,只执行一次
    
    console.log('页面load');
  },

  
  onReady: function () {
    // 监听页面第一次渲染完成
    // 只执行一次

    console.log('页面ready');
  },

  onShow: function () {
    // 只要页面显示,就会执行
     
    console.log('页面show');
  },


  onHide: function () {
    // 页面隐藏,就会执行
     
    console.log('页面hide');
  },


  onUnload: function () {
    // 页面卸载,就会执行
     
    console.log('页面unload');
  }
 
})


注意

1. tab页面之间的相互切换,不会让页面重新加载(onLoad),也就不会卸载(onUnload),只会隐藏与显示页面,即:页面切换只会交替执行 onHide() 与 onShow() 函数

2. 在某页面使用 NavigatorTo 跳转至目标页面时(比如从 index 页面跳转至 detail 页面),该页面(index页面)只执行 onHide(), 目标页面(detail页面)执行 onLoad()、onReady()、onShow();

3. 在回退(NavigatorBack)时(比如从 detail 页面回退至 index 页面),index页面执行onShow(), detail页面会被卸载,即执行onUnload();

原文地址:https://www.cnblogs.com/cckui/p/10006375.html