微信小程序-授权登录退出与缓存

我们的项目开发多多少少的都会用到用户的一些信息,比如头像,昵称,性别等。而这些信息的获取,小程序也为我们提供好了方法。

1,认识wx.getUserProfile方法

对应的文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html 

2,授权弹窗

一般我的使用上面的wx.getUserProfile方法获取用户信息时,需要用户授权的。一般授权弹窗如下。

 只有用户点击允许以后才可以获取用户信息。

不弹起授权弹窗解决方案

有的同学用这个方法时,不会弹起上面的弹窗,有可能是因为基础库版本太低,这里建议升级到最新版的基础库。

3,登录成功

 

 

4,授权登录退出与缓存核心代码

wxml:

<button wx:if="{{!userInfo}}" bindtap="login" class="denglu">授权登录</button>
<view wx:else class="root">
  <image class="touxiang" src="{{userInfo.avatarUrl}}"></image>
  <view class="nicheng">{{userInfo.nickName}}</view>
  <button  bindtap="loginOut">退出登录</button>
</view>

wxss:

.denglu{
  color: blue;
}
.root{
  display: block;
  justify-content:center;
  align-items: center;
}
.touxiang{
  width: 200rpx;
  height: 200rpx;
  border-radius: 100px;
  margin-top: 30rpx;
  margin-bottom: 10rpx;
  margin-left: 280rpx;
}
.nicheng{
  margin-left: 335rpx; 

  
}

js:

Page({
  data:{
    userInfo:""
  },
  onLoad(){
    let user=wx.getStorageSync('user')
    console.log("进入小程序的index页面获取缓存",user)
    this.setData({
      userInfo:user
    })
  },
  //登录
  login(){
    console.log("点击事件执行了")
    wx.getUserProfile({
      desc: '必须授权才可以继续使用',
      success:res=> {
        let user=res.userInfo
        //把用户信息缓存到本地
        wx.setStorageSync('user', user)
        console.log("授权成功",res.userInfo)
        this.setData({
         userInfo:res.userInfo
        })
      },
      fail:res=> {
        console.log("授权失败,请检查网络")
      }
    })
  },
  //退出登录
  loginOut(){
    this.setData({
      userInfo:""
     })
     wx.setStorageSync('user', null)
  }
})

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值