小程式開發中獲取使用者頭像和暱稱
阿新 • • 發佈:2019-01-26
獲取使用者頭像和暱稱:
<!--index.wxml--> <view class="container"> <view bindtap="bindViewTap" class="userinfo"> <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image> <text class="userinfo-nickname">{{userInfo.nickName}}</text> </view> <view class="usermotto"> <text class="user-motto">{{motto}}</text> </view> </view>
/**index.wxss**/
.userinfo {
display: flex;
flex-direction: column;
align-items: center;
}
.userinfo-avatar {
width: 128rpx;
height: 128rpx;
margin: 20rpx;
border-radius: 50%;
}
.userinfo-nickname {
color: #aaa;
}
.usermotto {
margin-top: 200px;
}
//index.js //獲取應用例項 var app = getApp() Page({ data: { motto: 'Hello World', userInfo: {} }, //事件處理函式 bindViewTap: function() { wx.navigateTo({ url: '../logs/logs' }) }, onLoad: function () { console.log('onLoad') var that = this //呼叫應用例項的方法獲取全域性資料 app.getUserInfo(function(userInfo){ //更新資料 that.setData({ userInfo:userInfo }) }) } })
呼叫登陸介面 app.js
//app.js App({ onLaunch: function () { //呼叫API從本地快取中獲取資料 // var logs = wx.getStorageSync('logs') || [] // logs.unshift(Date.now()) // wx.setStorageSync('logs', logs) }, 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) } }) } }); } }, globalData:{ userInfo:null } })