三種微信小程序獲取用戶頭像昵稱的方式


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
    })
  }
})
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2024 CODEPRJ.COM