1.在data中定义一个userInfo:''
2.在页面绑定点击事件
<button bindtap="getUserProfile" wx:else="">微信登陆</button>
3.通过点击事件获取用户信息
// 获取用户信息
getUserProfile() {
wx.getUserProfile({
desc: '用于完善会员资料',
success: (res) => {
this.setData({
userInfo: res.userInfo,
// hasUserInfo: true
})
// 把用户信息储存到storage中
wx.setStorage({
key: "user",
data: res.userInfo
})
// 登陆时获取code码
wx: wx.login({
success: (res) => {
if (res.code) {
wx.request({
url: `https://api.weixin.qq.com/sns/jscode2session?appid=wx5dfafee5cc7155e9&secret=7152efa3f16049127fa53f934dcc9ba3&js_code=${res.code}&grant_type=authorization_code`,
})
}
},
// fail: (res) => {},
})
}
})
},
4.生命周期函数,监听页面加载
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
wx.getStorage({
key: "user",
success: (res) => {
this.setData({
userInfo: res.data
})
}
})
},