微信小程序登录授权功能wx.login

wx.authorize wx.getSetting()

用户信息授权getUserInfo()

//app.js
//663788ae7486bf62f09d09049f44e8b0
App({
  globalData:{
    userInfo
  },
  onLaunch(){
    wx.getSetting({
      success:res=>{
        //如果已经验证
        console.log('1')
        if(res.authSetting['scope.userInfo']){
          wx.getUserInfo({
            success:res=>{
              //放到globalData中
              this.globalData.userInfo = res.userInfo
              //异步调用
              if(this.userInfoReadyCallback){
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  }
})
//detail.js
const app = getApp()
Page({
  data:{
    canIUse:wx.canIUse("button.open-type.getUserInfo"),
    userInfo:"",
    hasUserInfo:false,
  },
  onLoad:function(){
    if(app.globalData.userInfo){
    	console.log(1)
        this.setData({
          userInfo:app.globalData.userInfo,
          hasUserInfo:true
        })
    }else if(this.data.canIUse){
    	console.log(2)
      var self = this
      app.userInfoReadyCallback(res=>{
      	console.log(3)
        selt.setData({
          userInfo:res.userInfo,
          hasUserInfo:true
        })
      })
    }else{
    	console.log(4)
      wx.getSetting({
        success:res=>{
          this.setData({
            userInfo:res.userInfo,
            hasUserInfo:true
          })
        }
      })
    }
  },
  getUserInfo(e){
  	 if(!e.detail.userInfo){
		return
	}
	console.log(5this.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo:e.detail.userInfo,
      hasUserInfo:true
    })
  }
})

<button open-type="getUserInfo" bindgetUserInfo="getUserInfo" wx:if="{{!hasUserInfo && canIUse}}">获取头像昵称button>

代码逻辑如下:
//清空缓存,第一次进入detail页面
0—2
点击获取头像昵称按钮
允许
5
拒绝
什么都没有发生 return了
允许之后,刷新页面,二次进入
0—1
如果网络有延迟,可能会出现
0—2---3 触发回调

个人体会,过多的回调函数,函数嵌套,异步写法,利用传统的js回调函数类型的编程,会大大增加程序的复杂性,难以直观清楚的解析代码逻辑和数据的流动方向

你可能感兴趣的:(微信小程序)