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

小程式獲取使用者資訊(1)

 1. app.js

getUserInfo: function (cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //呼叫登入介面
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },

2. .wxml

<view  bindtap="bindViewTap" class="userinfo">
    <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>
    <text class="userinfo-nickname">{{userInfo.nickName}}</text>
</view>

3. .js

/**
   * 頁面的初始資料
   */
data: {
    userInfo: {},
  },
/**
   * 生命週期函式--監聽頁面載入
*/
onLoad: function (options) {
    var that = this
    //呼叫應用例項的方法獲取全域性資料
    app.getUserInfo(function (userInfo) {
      //更新資料
      that.setData({
        userInfo: userInfo
      })
    })
  }

4. .wxss

.userinfo{
  height:200px;
  display: flex;
  flex-direction: column;
  justify-content:center; 
  align-items: center
}
.userinfo-avatar{
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

效果: