uniapp页面生命周期函数执行时机

发布时间 2023-10-17 16:58:09作者: 小旭的blog

一、总览 

 

二、分析

通过浏览器控制台得到:

从上述实验我们可以得到以下结论:

onLoad 对应 created, onReady 对应 mounted, 不过uniapp页面生命周期函数执行时机略早于组件生命周期函数,在页面级vue文件中可优先考虑使用页面级生命周期函数。
需要依赖页面传参逻辑的需使用onLoad
在切换浏览器窗口时会频繁调用 onHide 和 onShow, 而其他生命周期函数则不会再调用,所以比较保守的做法是把接口调用写在onShow里,这样每次页面展示都会获取最新数据。

三、代码 

  onInit(){
    //仅百度小程序
    console.log('this is oninit--------'+ new Date().getTime())
  },
  beforeCreate() {
    console.log('// 进入路由')
    console.log('this is beforeCreate--------'+ new Date().getTime())
  },
  onLoad(query){
    //data, computed, method, prop, slots已经设置完成, 参数为上个页面传递的数据
    console.log('this is onload--------'+ new Date().getTime())
  },
  onShow(){
    //页面每次出现在屏幕上都触发,切换窗口会频繁触发onHide和onShow
    console.log('onshow获取$el:'+this.$refs.myNav) // 第一次进入页面为undefined,切换窗口则后续能获取到
    console.log('this is onshow-------'+ new Date().getTime())
  },
  created(){
    console.log('this is created-------'+ new Date().getTime())
  },
  beforeMount(){
    console.log('this is beforeMount-------'+ new Date().getTime())
  },
 
  onReady(){
    //页面渲染完成,dom树可用
    console.log('this is onready-------'+ new Date().getTime())
  },
  mounted(){
    console.log('this is mounted-------'+ new Date().getTime())
  },
 
  onHide(){
    // 页面隐藏,切换浏览器窗口时调用
    console.log('// 切换页面')
    console.log('this is onhide-------'+ new Date().getTime())
  },
  onUnload(){
    // 页面卸载, 切换路由时调用
    console.log('// 离开路由')
    console.log('this is onUnload-------'+ new Date().getTime())
  },
  beforeDestroy(){
    console.log('this is beforeDestroy-------'+ new Date().getTime())
  },
  destroyed(){
    console.log('this is destroyed-------'+ new Date().getTime())
  },