小程序的登录授权与退出功能(wx.getUserProfile)

一、授权登录:wx.getUserProfile

1、使用wx.getUserProfile实现登录

1、javascript:
  login(){
    wx.getUserProfile({
      desc: '用于完善信息资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: res => {
        let user=res.userInfo
      console.log('内部的this',user)
       this.setData({
        nickName: user.nickName,
        touxiang: user.avatarUrl
       })
     },
     fail:res=>{
       console.log('失败',res)
     }
    })
  }

2、使得头像美观,头像和名字居中对齐

1、html:
<button bindtap="login">授权登录</button>
<view class="user">
<image class="touxiang" src="{{touxiang}}"></image>
<view class="name">{{nickName}}</view>
</view>
2、css:
.user{
  display: flex;
  flex-direction: column;
  align-items: center;
}
.touxiang{
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  margin-top: 30rpx;
  margin-bottom: 30rpx;
}

二、授权登录后使得授权按钮自动隐藏

1、第一种方式

1、html:
<button bindtap="login" wx:if="{{NoLogin}}">授权登录</button>
<view class="user" wx:else>
<image class="touxiang" src="{{touxiang}}"></image>
<view class="name">{{nickName}}</view>
</view>
2、javascript:
  /**
   * 页面的初始数据
   */
  data: {

    NoLogin:true,
    nickName:''
  },  
  login(){
    wx.getUserProfile({
      desc: '用于完善信息资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: res => {
        let user=res.userInfo
      console.log('内部的this',user)
       this.setData({
        nickName: user.nickName,
        touxiang: user.avatarUrl,
        NoLogin:false
       })
     },
     fail:res=>{
       console.log('失败',res)
     }
    })
  }

2、第二种方式(推荐:代码量少)

1、html:
<button bindtap="login" wx:if="{{!userInfo}}">授权登录</button>
<view class="user" wx:else>
<image class="touxiang" src="{{userInfo.avatarUrl}}"></image>
<view class="name">{{userInfo.nickName}}</view>
</view>
2、javascript:
 /**
   * 页面的初始数据
   */
  data: {
    userInfo:'',
    nickName:''
  },
  login(){
    wx.getUserProfile({
      desc: '用于完善信息资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: res => {
        let user=res.userInfo
      console.log('内部的this',user)
       this.setData({
        userInfo:user
       })
     },
     fail:res=>{
       console.log('失败',res)
     }
    })
  }

三、退出功能

使用上文的授权判断{{!userInfo}}语句,授权是把res.userInfo的信息交给user使得判断语句为假,而退出的让判断语句为真,所以代码可以写成:

1、javascript:
  // 退出登录
  loginOut(){

    this.setData({
      userInfo:''
     })
  }
posted @ 2022-05-26 19:53  小白学CS  阅读(651)  评论(0编辑  收藏  举报