微信小程序笔记——微信小程序appjs的onLaunch执行完之后再执行Page的onLoad

一:前言

小程序网络请求默认为异步请求,在appjs的onLaunch运行后进行异步请求时,程序不会停止,Page页已执行onload, 我们希望onLaunch执行完后再执行onload。

解决方法:定义回调函数

//app.js

App({
  onLaunch: function () {
    let _this = this;
    wx.request({
      url: 'http://test.cn/login', //仅为示例,并非真实的接口地址
      data: {},
      success: function(res) {
        _this.globalData.checkLogin = true;
        //由于这里是网络请求,可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (_this.checkLoginReadyCallback){
           _this.checkLoginReadyCallback(res);
        }
      }
    })
  },
  globalData: {
    checkLogin: false
  }
})


//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    test: false
  },
  onLoad: function () {
    let that = this;
    //判断onLaunch是否执行完毕
    if (app.globalData.checkLogin){
      that.setData({
        test:true
      })
    }else{
      app.checkLoginReadyCallback = res => {
        that.setData({
          test:true
        })
      };
    }
  }
})

执行顺序:[App] onLaunch -> [Page] onLoad -> [App] onLaunch sucess callback-> [Page] onLoad

  • 1
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值