uni小程序app中異步請(qǐng)求尚未執(zhí)行完成,就執(zhí)行Page頁(yè)面請(qǐng)求的問題

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'], // 主動(dòng)
    // scopes: ["auth_user"], // 主動(dòng)
    // #endif
    success: (res) => {
      console.log('默認(rèn)登錄', 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);
            // 由于這里是網(wǎng)絡(luò)請(qǐng)求,可能會(huì)在 Page.onLoad 之后才返回  所以此處加入 callback 以防止這種情況
            console.log('app this', this);
            if (this.$scope.testDataCallback) {
              console.log('有回調(diào)', this);
              this.$scope.testDataCallback(res.data);
            }
          })
          .catch((err) => {
            console.log('小程序登錄失敗', err);
            // #ifdef MP-WEIXIN
            log.error('小程序登錄失敗', err);
            // #endif
          });
      } else {
        console.log('獲取用戶登錄態(tài)失敗!' + res.errMsg);
        // #ifdef MP-WEIXIN
        log.error('獲取用戶登錄態(tài)失敗!' + res.errMsg);
        // #endif
      }
      this.globalData.isLogin = true;
    },
    fail: (err) => {
      console.log('登陸失敗', err);
      uni.hideLoading();

      uni.showToast({
        title: '登錄失敗',
        icon: 'none',
      });
      // #ifdef MP-WEIXIN
      log.error('小程序授權(quán)登錄失敗', err);
      // #endif
    },
  });
},

index.vue

if (app.globalData.token) {
  console.log('首頁(yè)有token', v);
  this.init();
} else {
  // 聲明回調(diào)函數(shù)獲取app.js onLaunch中接口調(diào)用成功后設(shè)置的 globalData 數(shù)據(jù)
  console.log('首頁(yè)沒有token', app);
  app.testDataCallback = (res) => {
    console.log('首頁(yè)登錄后執(zhí)行init');
    this.init();
  };
}

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容