文章目录
一、授权登录:wx.getUserProfile
1、使用wx.getUserProfile实现登录
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、使得头像美观,头像和名字居中对齐
<button bindtap="login">授权登录</button>
<view class="user">
<image class="touxiang" src="{{touxiang}}"></image>
<view class="name">{{nickName}}</view>
</view>
.user{
display: flex;
flex-direction: column;
align-items: center;
}
.touxiang{
width: 200rpx;
height: 200rpx;
border-radius: 50%;
margin-top: 30rpx;
margin-bottom: 30rpx;
}
3、授权登录后使得授权按钮自动隐藏
3.1、第一种方式
<button bindtap="login" wx:if="{{NoLogin}}">授权登录</button>
<view class="user" wx:else>
<image class="touxiang" src="{{touxiang}}"></image>
<view class="name">{{nickName}}</view>
</view>
/**
* 页面的初始数据
*/
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)
}
})
}
3.2、第二种方式(推荐:代码量少)
<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>
/**
* 页面的初始数据
*/
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使得判断语句为假,而退出的让判断语句为真
所以代码可以写成:
// 退出登录
loginOut(){
this.setData({
userInfo:''
})
}

本文介绍了如何在微信小程序中实现用户授权登录和退出功能。通过wx.getUserProfile获取用户信息,设置头像和昵称居中显示,并在授权成功后自动隐藏登录按钮。退出功能则清空用户信息,重新显示登录按钮。提供了两种不同的实现方式,简化代码逻辑。

2339

被折叠的 条评论
为什么被折叠?



