微信小程序授权登录

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

以上代码先判断是否有用户记录,如果没有,就显示授权登录按钮,否则就显示我们的用户信息 然后我们先修改一下我们的组件的样式,我们打开index.wxss,修改代码如下:

.root{
          
   
    display: flex;
    flex-direction: column;
    align-items:center;
}
.touxiang{
          
   
    width:200rpx;
    height:200rpx;
    border-radius:50%;
    margin-top:30rpx;
    margin-bottom:10rpx;
}

然后我们进入index.js文件,修改代码如下:

Page({
          
   
    data:{
          
   
    //用户信息开始为空
       userInfo:
    },
    onLoad(){
          
   
        //获取本地缓存
        let user=wx.getStorageSync(user)
        console.log("进入小程序的index页面获取缓存",user)
        this.setData({
          
   
            userInfo:user
        })
    },
    //授权登录
    login(){
          
   
        wx.getUserProfile({
          
   
            desc:必须授权后才能继续使用,
            success:res=>{
          
   
                let user=res.userInfo
                //设置本地缓存,把用户信息缓存到本地
                wx.setStorageSync(user,user)
                console.log(用户信息,user)
                this.setData({
          
   
                    userInfo:user
                })
            }
        })
    },
    //退出登录
    loginOut(){
          
   
        this.setData({
          
   
            userInfo:
        })
        wx.setStorageSync(user,null)
    }
})

我们点击编译,再点击模拟器,因为一开始没有缓存,所以显示授权按钮 点击授权登录 再点击允许 现在有缓存了,我们再次点击编译,因为有本地缓存,所以直接进入上面的页面,不需要重新授权登录,我们再点击退出登录 点击退出登录后,缓存也会被清空,下次使用小程序时,就要重新授权登录

经验分享 程序员 微信小程序 职场和发展