微信小程序獲取用戶信息的兩種方法wx.getUserInfo與open-data實例分析

這篇文章主要介紹了微信小程序獲取用戶信息的兩種方法wx.getUserInfo與open-data,結合實例形式分析了wx.getUserInfo與open-data獲取用戶信息的相關操作技巧與使用注意事項,需要的朋友可以參考下

本文實例講述了微信小程序獲取用戶信息的兩種方法wx.getUserInfo與open-data。分享給大家供大家參考,具體如下:

在此之前,小程序獲取微信的頭像,暱稱之類的用戶信息,我用的都是wx.getUserInfo,例如:

onLoad: function (options) {
  var that = this;
  //獲取用戶信息
  wx.getUserInfo({
    success: function (res) {
      console.log(res);
      that.data.userInfo = res.userInfo;
      that.setData({
        userInfo: that.data.userInfo
      })
    }
  })
},

wx.getUserInfo需要用戶授權scope.userInfo,也就是那個授權彈窗。

但是!!!重點來了,自從微信接口有了新的調整之後 這個wx.getUserInfo()便不再出現授權彈窗了,需要使用button做引導~

<!--wxml-->
<!-- 需要使用 button 來授權登錄 -->
<button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授權登錄</button>
<view wx:else>請升級微信版本</view>

js:

Page({
 data: {
  canIUse: wx.canIUse('button.open-type.getUserInfo')
 },
 onLoad: function() {
  // 查看是否授權
  wx.getSetting({
   success: function(res){
    if (res.authSetting['scope.userInfo']) {
     // 已經授權,可以直接調用 getUserInfo 獲取頭像暱稱
     wx.getUserInfo({
      success: function(res) {
       console.log(res.userInfo)
      }
     })
    }
   }
  })
 },
 bindGetUserInfo: function(e) {
  console.log(e.detail.userInfo)
 }
})

這就是等於一步變兩步了~現在用button的話 可以在產品上多加引導,不會顯得那麼突兀的出來一個彈窗了

然鵝,如果你僅僅只是想展示用戶信息的話,那便使用open-data 吧,如下:

<!-- 如果只是展示用戶頭像暱稱,可以使用 <open-data /> 組件 -->
<open-data type="userAvatarUrl"></open-data>
<open-data type="userNickName"></open-data>

只需要這兩行wxml的代碼,便可展示微信暱稱和頭像,是不是很驚喜!

希望本文所述對大家微信小程序開發有所幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章