mpvue里created里异步请求结果,如何在beforeMount里获取到呢

问题描述

用mpvue做小程序时,要在首页展示轮播图之前获取到token,openId,并在请求获取轮播图时候在header里传进去,后面所有接口都需要这两个头部信息。我想在created里获取到这两个结果,存在storage里在beforeMount里调用,可是不能行

之前我是直接用new Promise一路then下来,最后一个then里调用轮播方法传进去openId和token,想问下还有别的方法吗

this.$http是flyIO挂载在vue原型上

created(){
this.checkIt()
.then(function (res) {

console.log('index首页登录----成功')
var code = wx.getStorageSync('code')
var appId = wx.getStorageSync('appId')
var openId = wx.getStorageSync('openId')
var token = wx.getStorageSync('token')
console.log(code, appId, openId, token)

})
.catch(function (res) {

console.log('失败')
that.login()
  .then(function (res) {
    console.log(res)
    that.getId(res)
      .then(that.$http.spread(function (res1, res2) {
      // 两个请求都完成
        var openId = res1.data.data.open_id
        var token = res2.data.data
        console.log(openId, token)
        wx.setStorageSync('openId', openId)
        wx.setStorageSync('token', token)
        // 最后,调用轮播等接口传进去openId和token,有没有其他封装方法
      }))
      .catch(function (error) {
        console.log(error)
      })
  }).catch(function (err) {
    console.log(err)
  })

})
},
methods: {

checkIt () {
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success (res) {
        resolve(res)
      },
      fail (res) {
        reject(res)
      }
    })
  })
},
login () {
  return new Promise((resolve, reject) => {
    wx.login({
      success (res) {
        resolve(res)
      },
      fail (err) {
        reject(err)
      }
    })
  })
},
getId (res) {
  return new Promise((resolve, reject) => {
    // 成功后获取code
    let code = res.code
    console.log('code码是:-->' + code)
    var accountInfo = wx.getAccountInfoSync()
    var appId = accountInfo.miniProgram.appId
    console.log('appId码是:-->' + appId)
    wx.setStorageSync('code', code)
    wx.setStorageSync('appId', appId)
    var url = baseUrl+'/shop/weixin/login?code=' + code + '&appId=' + appId
    var url2 = baseUrl+'/login/userInfo?appId=' + appId

    return this.$http.all([this.getOpenId(url), this.getToken(url2)])
      .then((res1, res2) => {
        resolve(res1, res2)
      })

}

有没有解决方法是,加载完了created后,这些信息存在storage里,在beforeMount里能取到值,而不是都在then里

阅读 2.6k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题