<>一、解题思路:

微信授权登录(获取用户信息)
1.先获取用户信息——用户授权允许后,通过调用uni.login 可以获取到code。
2.拿着获取到的code去调用——登录接口,可以获取到token。
3.把token存入缓存。就可以在页面判断是否登录了。

<>二、代码
<view @click="getUserInfo()">点击登录</view> <script> export default { data() {
return { localtoken: '' } }, onLoad() {}, onHide() {}, onShow() {
this.localtoken= uni.getStorageSync('localtoken'); }, methods: { getUserInfo() {
var that= this; uni.showLoading({ // 展示加载框 title: '加载中', }); uni.getUserProfile
({ //获取到用户信息 desc: '登录后可同步数据', success: async (obj) => { console.log('obj', obj)
; that.nickName = obj.userInfo.nickName //用户名 that.avatarUrl =
obj.userInfo.avatarUrl //用户头像 // 调用 action ,请求登录接口 uni.login({ provider:
'weixin', success: (res) => { console.log('res-login', res); //获取到code that.code
= res.code; // console.log('code', res.code); //请求登录接口 if (res.errMsg ==
'login:ok') { var params = { code: that.code, nickname: that.nickName, avatar:
that.avatarUrl} that.$api.appPlateForm('POST', 'auth/login', params, function(
res) { if (res.code == 200) { uni.showToast({ title: '登录成功', icon: 'success',
mask: true,}); //获取到token 存入缓存。通过有无token来判断是否登录 // console.log('登录接口',res)
uni.setStorageSync('localtoken', res.data.data.access_token) that.myProfile()
//用户信息接口 that.getHistoryList() //足迹接口 } }, function(err) { uni.showToast({ icon:
'none', title: err.msg }) }); } }, }); }, fail: () => { uni.showToast({ title:
'授权已取消', icon: 'error', mask: true, }); }, complete: () => { // 隐藏loading
uni.hideLoading(); }, }); }, //退出登录 logOut() { var that = this uni.showModal({
title:'确定要退出登录吗?', success: function(res) { if (res.confirm) {
uni.removeStorageSync('token') that.nickname = '' that.headimgurl = '' } else if
(res.cancel) { // console.log('用户点击取消'); } } }); }, } } </script>
<>三、效果展示

<>ending~

技术
今日推荐
PPT
阅读数 121
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信