likes
comments
collection
share

微信小程序app.js的onLaunch执行完之后再执行Page的onLoad & 小程序onLaunch和onLoad执行顺序

作者站长头像
站长
· 阅读数 4

需求

在微信小程序分享页面时,打开页面按理应该是先走完app.jsonLaunch onShow执行分享页面onLoadonShow;但现因为app.jsonLaunch异步操作,在等待返回值的时候Page里的onLoad事件就已经执行了。

想要的结果

[App] onLaunch -> [Page] onLoad -> [App] onLaunch sucess callback-> [Page] onLoad

具体实现案例

1、app.js

//app.js
 App({
  onLaunch () {
   wx.request({
    url: '接口', //仅为示例,并非真实的接口地址
    data: {
    },
    success(res)=> {
    this.globalData.haveLoginFlag= res.data.haveLoginFlag;
     // 所以此处加入 callback 以防止这种情况
     if (this.checkLoginReadyCallback){
      this.checkLoginReadyCallback({haveLoginFlag:res.data.haveLoginFlag});
     }
    }
   })
  },
  globalData: {
   haveLoginFlag: false
  }
 })

2、分享页面的page

const app = getApp()
  onLoad() {
  //判断app.js onLaunch是否执行完毕
    if (app.globalData.haveLoginFlag) {
      const { spuId, selectedAddr } = this.data;
      const newAddr = wx.getStorageSync('addressMsg');
      if (selectedAddr.addressId != newAddr?.addressId) {
        this.getDetail(spuId);
      }
    } else {
      app.checkLoginReadyCallback = res => {
      if(res.haveLoginFlag){
        const { spuId, selectedAddr } = this.data;
        const newAddr = wx.getStorageSync('addressMsg');
        if (selectedAddr.addressId != newAddr?.addressId) {
          this.getDetail(spuId);
         }
        }
      }
    }
  }

相关文章

基于ElementUi再次封装基础组件文档


基于ant-design-vue再次封装基础组件文档


vue3+ts基于Element-plus再次封装基础组件文档