//js
Page({
data: {
userInfo: {},
hasUserInfo: false,
},
onLoad: function() {
const that=this;
wx.login({
success (res) {
that.getUserProfile();
console.log(res);
console.log(that.data.userInfo);
}
})
},
getUserProfile(){
wx.showLoading({
title: '加载中',
});
//如果不点击只能运行到这里
wx.getUserProfile({
desc: 'nickname',
success:(res)=>{
console.log(res);
this.setData({userInfo:res.userInfo,hasUserInfo:true});
wx.hideLoading();
}
});
}
}
);
wxml:
<view class="container">
<view class="userinfo">
<!-- 如果没有用户信息,只显示获取用户信息的按钮 -->
<block wx:if="{{!hasUserInfo}}">
<button bind:tap="getUserProfile">若登陆失败,点此显示信息</button>
</block>
<!-- 如果有用户信息,显示用户头像和昵称 -->
<block wx:else>
<text>{{userInfo.nickName}}</text>
<image src="{{userInfo.avatarUrl}}" mode="widthFix"/>
</block>
</view>
</view>
现在都不建议用wx.getUserProfile了,因为获取的也是微信用户,默认头像了,取不到真实用户昵称和头像,参考,建议该需求页面吧,用户自己编辑
https://developers.weixin.qq.com/community/develop/doc/00022c683e8a80b29bed2142b56c01
wx.getUserProfile 接口需要有点击事件才能调用:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html