添加事件
<button class="user_btn" open-type="getUserProfile" @tap="getUserProfile">去登录</button>
在获取用户信息成功的回调函数中调用下一个函数,下一个函数使用成功回调的数据发送请求获取token,实现登录。
获取用户信息:
async getUserProfile() {
await wx.getUserProfile({
desc: "用于完善用户资料",
//异步请求:回调函数中调用下一个函数
success: (res) => this.onSaveUserInfo(res),
});
},
async onSaveUserInfo(e) {
const { userInfo, encryptedData, rawData, iv, signature } = e;
//通过解构赋值提取出 code (验证码)
const [, { code }] = await uni.login();
// 使用拿到的数据发送请求获取token
const res = await this.$u.api.getUserToken({
encryptedData,
rawData,
iv,
signature,
code,
});
// message 对象不为空,才能获取到 token
if (res.message) {
// 提取出 token
const { token } = res.message;
// 把 token 保存到本地
uni.setStorageSync("token", token);
// 获取到token 才渲染用户头像
this.userInfo = userInfo;
uni.setStorageSync("userInfo", userInfo);
} else {
// 登录错误提示
uni.showToast({ title: "登录错误,请重试", icon: "none" });
}
},