本文實例講述了微信小程序獲取用戶信息的兩種方法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的代碼,便可展示微信昵稱和頭像,是不是很驚喜!
希望本文所述對大家微信小程序開發有所幫助。
新聞熱點
疑難解答