index.wxml
<view class="container">
<view class="userinfo">
<block wx:if="{{canIUseOpenData}}" calss="userinfo-opendata">
<view class="userinfo-avatar" bindtap="bindViewTap">
<open-data type="userAvatarUrl"></open-data> <!-- 直接顯示微信頭像 具體可參照官網組件open-data -->
</view>
<open-data type="userNickName"></open-data> <!-- 直接顯示微信昵稱 具體可參照官網組件open-data-->
</block>
<block>
<button bindtap="getUserProfile"> 獲取頭像昵稱 </button>
<button open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 獲取頭像昵稱1 </button>
</block>
<block>
<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</block>
</view>
</view>
idex.js
Page({
data: {
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo'),
canIUseGetUserProfile: false,
canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需嘗試獲取用戶信息可改為false
},
// 事件處理函數
bindViewTap() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad() {
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
}
},
getUserProfile(e) {
// 推薦使用wx.getUserProfile獲取用戶信息,開發者每次通過該接口獲取用戶個人信息均需用戶確認,開發者妥善保管用戶快速填寫的頭像昵稱,避免重復彈窗
wx.getUserProfile({
desc: '展示用戶信息', // 聲明獲取用戶個人信息后的用途,后續會展示在彈窗中,請謹慎填寫
success: (res) => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
},
getUserInfo(e) {
// 不推薦使用getUserInfo獲取用戶信息,自2021年4月13日起,getUserInfo將不再彈出彈窗,並直接返回匿名的用戶個人信息
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
}
})