微信小程序 获取用户信息 getUserInfo

获取用户信息(wx.getUserInfo())

该方法使用需要 用户授权 scope.userInfo 之后才能调用

写个小案例

wxml

<button type="primary" open-type="getUserInfo" bindgetuserinfo="getUserInfo">询问是否同意授权并获取用户信息</button>
<view class="container">
  <text>{
   
   { userInfo.nickName }}</text>
  <text>{
   
   {userInfo.city}}</text>
  <text>{
   
   {userInfo.province}}</text>
  <text>{
   
   {userInfo.language}}</text>
  <image src='{
   
   { userInfo.avatarUrl }}'></image>
</view>

.js

  data: {
    userInfo: {},
  },
  getUserInfo:function(){
    let that = this
    //首先查看是否得到用户 的授权
    wx.getSetting({
      success:function(res){
        //console.log(res)
        //res.authSetting['scope.userInfo']   代表用户授予权限的状态
        console.log(res.authSetting['scope.userInfo'])
        if(res.authSetting['scope.userInfo']){
          //如果用户给与了这个权限 可以进行获取用户信息
          wx.getUserInfo({
            success: (res) => {
              console.log(res.userInfo)
              that.setData({
                userInfo: res.userInfo
              })
            }
          })
        }else{
          //如果用户没有给与这个权限则  发送询问权限的请求
          wx.authorize({
            scope:"scope.userInfo",//询问授权的属性
            success:function(res){
              console.log(res)
            }
          })
        }
      }
    })
  },

注: 回调中的 this 和 当前页面 this 不一样 解决方案,1:使用 ES 6 语法, 2:定义 that(let that = this 然后 that.data)

es6语法 

wx.getUserInfo({
      success: (data) => {
        this.setData({
          // 如何确定数据被更新?调试器中 AppData
          userInfo: data.userInfo
        })
      }
    })

猜你喜欢

转载自blog.csdn.net/weixin_41040445/article/details/114603268