1. 程式人生 > >小程式 獲取使用者資訊

小程式 獲取使用者資訊

index.js頁面

//index.js
//獲取應用例項
const app = getApp()

Page({
  data: {
    userInfo: {},
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
      })
    } else if (this.data.canIUse){
      // 由於 getUserInfo 是網路請求,可能會在 Page.onLoad 之後才返回
      // 所以此處加入 callback 以防止這種情況
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
        })
      }
    } else {
      // 在沒有 open-type=getUserInfo 版本的相容處理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    if (app.userInfoReadyCallback){
        app.userInfoReadyCallback(e.userInfo);
     }else{
        this.setData({
          userInfo: e.detail.userInfo,
        })
     }
    app.globalData.userInfo = e.detail.userInfo
  }
})

index.wxml

<button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo">獲取頭像暱稱</button>