微信小程序——授权

版权声明:尊重作者,热爱开发! https://blog.csdn.net/qq_38290251/article/details/83074247

/**

* 生命周期函数--监听页面加载 onLoad

*/

let userInfo = app.globalData.userInfo

if (!(!userInfo && typeof userInfo != "undefined" && userInfo != 0)) {

    this.setData({

        userInfo,

        hasUserInfo: true,

    })

} else if (this.data.canIUse) {

    // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回

    // 所以此处加入 callback 以防止这种情况

    app.userInfoReadyCallback = res => {

        console.log('userInfoReadyCallback')

        this.setData({

            userInfo: res,

            hasUserInfo: true

        })
    
    }

}
<button class="submit-btn" wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo">免费领取</button>

<view class="submit-btn" wx:else>请升级微信版本</view>
/**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //未授权点击弹出授权
  getUserInfo(e) {
    console.log('点击授权 getUserInfo:', e)

    if (e.detail.errMsg === 'getUserInfo:ok') {

      let userInfo = e.detail
      app.func.putCache('userInfo', userInfo)
      app.globalData.userInfo = userInfo
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true
      })

      $wxLogin().then(res => {
        let code = res.code
        wx.setStorageSync("code", code)
        return code
      }).then(res => {

            //逻辑

      })

    } else {
      // 取消授权
      $toast('取消授权')
    }

  },

猜你喜欢

转载自blog.csdn.net/qq_38290251/article/details/83074247