小程序一般都需要在app.vue的onLaunch做一个异步请求获取用户的openId和token之后才能执行页面的onLoad里的异步请求,像平常用async await控制异步请求的先后顺序,

在小程序里也一样,只不是需要做成全局的。

如 :在main.js里挂载

Vue.prototype.$getToken = new Promise(resolve => {
  Vue.prototype.$isResolve = resolve;
})

然后在app.vue中

onLaunch: function () {
     let that=this;
     wx.login({
      success(res) {
        if (res.code) {
          // 发起网络请求 获取openId
          that.$http({
            url: "/wouu/applets/getToken",
            method: "post",
            data: {
              code: res.code,
            },
          }).then((res) => {
            console.log("999", res);
            //调用
            that.$isResolve();

          });
        } else {
          console.log("登录失败!" + res.errMsg);
        }
      },
    });
  },

在页面的onLoad()处

async onLoad() {
     // 等待登录结果返回
    await this.$getToken;
    this.$http({
      url:'/wdse/applets/qddSceewData',
      method:'post',
      data:{
        scene:'rdsmend',//场景值推荐
      }
    }).then(res=>{
      console.log('dssa',res)
    })
   
  },

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐