主要是通过在storage中缓存userInfo与清空userInfo的信息来实现登录与退出登录
wxml:
<view class="setting">
<view class="setting_thr" bindtap="login">
登录
</view>
</view>
<view class="setting">
<view class="setting_thr" bindtap="loginOut">
退出登录
</view>
</view>
wxss:
.setting {
width: 90%;
height: 80rpx;
padding: 20rpx;
margin-top: 20rpx;
background-color: #ffffff;
display: flex;
flex-direction: row;
}
.setting_thr{
width: 100%;
height: 40rpx;
padding: 10rpx;
margin-top: 10rpx;
font-size: 30rpx;
display: flex;
justify-content: center;
}
js:
Page({
data: {
userInfo: {},
},
})
onLoad() {
console.log("进入小程序")
let user = wx.getStorageSync('userInfo')
console.log("获取到的缓存", user)
this.setData({
userInfo: user
})
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
}
},
login() {
// 授权登录,获取用户信息
console.log("外部this:", this)
wx.getUserProfile({
desc: '用于完善会员资料',
success: res => {
console.log("内部this:", this)
console.log(res.userInfo)
let user = res.userInfo
// 用户信息缓存到本地
wx.setStorageSync('userInfo', user)
this.setData({
userInfo: user
})
},
fail: res => {}
})
},
loginOut() {
this.setData({
userInfo: ''
})
// 清除用户缓存
wx.setStorageSync('userInfo', null)
},
登录成功时storage缓存的userInfo信息:
退出登录时storage缓存的userInfo信息: