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

小程式獲取使用者資訊

getUserInfo

<button open-type="getUserInfo" bindgetuserinfo="getUserInfo">獲取資訊</button>
<block wx:if="{{userInfo}}">
  <text>{{userInfo.nickName}}</text>
  <text>{{userInfo.gender}}</text>
</block>
// pages/home/home.js
Page({

  /**
   * 頁面的初始資料
   */
  data: {
    userInfo: null
  },

  /**
   * 生命週期函式--監聽頁面載入
   */
  onLoad: function (options) {

  },

  /**
   * 生命週期函式--監聽頁面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命週期函式--監聽頁面顯示
   */
  onShow: function () {

  },

  /**
   * 生命週期函式--監聽頁面隱藏
   */
  onHide: function () {

  },

  /**
   * 生命週期函式--監聽頁面解除安裝
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函式--監聽使用者下拉動作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 頁面上拉觸底事件的處理函式
   */
  onReachBottom: function () {

  },

  /**
   * 使用者點選右上角分享
   */
  onShareAppMessage: function () {

  },
  getUserInfo: function(e) {
    if(e.detail.userInfo) {
      console.log(e.detail.userInfo);
      this.setData({
        userInfo: e.detail.userInfo
      })
    }
  }
})

GetUserProfile

<button bindtap="getUserInfo">獲取資訊</button>
<block wx:if="{{userInfo}}">
  <text>{{userInfo.nickName}}</text>
  <text>{{userInfo.gender}}</text>
</block>
// pages/home/home.js
Page({

  /**
   * 頁面的初始資料
   */
  data: {
    userInfo: null
  },

  /**
   * 生命週期函式--監聽頁面載入
   */
  onLoad: function (options) {

  },

  /**
   * 生命週期函式--監聽頁面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命週期函式--監聽頁面顯示
   */
  onShow: function () {

  },

  /**
   * 生命週期函式--監聽頁面隱藏
   */
  onHide: function () {

  },

  /**
   * 生命週期函式--監聽頁面解除安裝
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函式--監聽使用者下拉動作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 頁面上拉觸底事件的處理函式
   */
  onReachBottom: function () {

  },

  /**
   * 使用者點選右上角分享
   */
  onShareAppMessage: function () {

  },
  getUserInfo: function() {
    wx.getUserProfile({
      desc: "用於完善使用者體驗",
      success: res => {
        console.log(res.userInfo);
        this.setData({
          userInfo: res.userInfo
        })
      }
    })
  }
})