uni小程序app中异步请求尚未执行完成,就执行Page页面请求

2022-10-18  本文已影响0人  醉笙情丶浮生梦

uniapp全局静默登录
app.vue
$toast 是全局提示

getLogin() {
  console.log(this, '开始登录', this.$scope);

  this.$toast.showLoading();

  let accountInfo = wx.getAccountInfoSync();
  console.log('小程序信息', accountInfo);

  uni.login({
    // #ifdef MP-ALIPAY
    scopes: ['auth_base'], // 主动
    // scopes: ["auth_user"], // 主动
    // #endif
    success: (res) => {
      console.log('默认登录', res);
      if (res.code) {
        api
          .login({ code: res.code, vsnNum: accountInfo.miniProgram.version })
          .then((res) => {
            uni.hideLoading();

            if (!res.success) {
              this.$toast.showToast(res.msg);
              return;
            }
            console.log('登录成功', res);
            this.globalData.userInfo = res.data;
            this.globalData.token = res.data.token;

            uni.setStorageSync('token', res.data.token);
            // 由于这里是网络请求,可能会在 Page.onLoad 之后才返回  所以此处加入 callback 以防止这种情况
            console.log('app this', this);
            if (this.$scope.testDataCallback) {
              console.log('有回调', this);
              this.$scope.testDataCallback(res.data);
            }
          })
          .catch((err) => {
            console.log('小程序登录失败', err);
            // #ifdef MP-WEIXIN
            log.error('小程序登录失败', err);
            // #endif
          });
      } else {
        console.log('获取用户登录态失败!' + res.errMsg);
        // #ifdef MP-WEIXIN
        log.error('获取用户登录态失败!' + res.errMsg);
        // #endif
      }
      this.globalData.isLogin = true;
    },
    fail: (err) => {
      console.log('登陆失败', err);
      uni.hideLoading();

      uni.showToast({
        title: '登录失败',
        icon: 'none',
      });
      // #ifdef MP-WEIXIN
      log.error('小程序授权登录失败', err);
      // #endif
    },
  });
},

index.vue

if (app.globalData.token) {
  console.log('首页有token', v);
  this.init();
} else {
  // 声明回调函数获取app.js onLaunch中接口调用成功后设置的 globalData 数据
  console.log('首页没有token', app);
  app.testDataCallback = (res) => {
    console.log('首页登录后执行init');
    this.init();
  };
}

https://blog.csdn.net/wsln_123456/article/details/109464578
https://juejin.cn/post/6844904104456634382

上一篇下一篇

猜你喜欢

热点阅读