微信小程序-用户信息保存到本地
一.效果
二、实现
1.wxml实现
<view wx:if="{{userInfo != null}}">
<image class="LNU" src="{{userInfo.avatarUrl}}"
style="height: 120rpx; width: 120rpx; margin: 40rpx auto 10rpx auto; border-radius: 50%;"></image>
<view>
<text class="title123">
{{userInfo.nickName}}
</text>
</view>
<view class="padding flex flex-direction">
<button open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo"
class="cu-btn bg-green margin-tb-sm lg">登录成功</button>
</view>
</view>
<view wx:else>
<image class="LNU" src="../../images/LUNU.jpg"
style="height: 120rpx; width: 120rpx; margin: 40rpx auto 10rpx auto; border-radius: 50%;"></image>
<view>
<text class="title123">
辽大视窗
</text>
</view>
<view class="padding flex flex-direction">
<button open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo"
class="cu-btn bg-green margin-tb-sm lg">授权登录</button>
</view>
<view class="solids-bottom padding-xs flex align-center">
<view class="flex-sub text-center">
<view class="solid-bottom text-sm padding">
<text class="text-grey">Copyright © 2020 by lost | 辽宁大学 | 信息学院</text>
</view>
</view>
</view>
</view>
2.js实现
// pages/login/login.js
var that;
Page({
/**
* 页面的初始数据
*/
data: {
userInfo:null,
},
bindGetUserInfo(e){
//this:这个页面整个对象
var that = this;
console.log(e);
if(e.detail.userInfo){
//存储到本地
wx.setStorage({
//序列化
data: JSON.stringify(e.detail.userInfo),
key: 'userInfo',
success(res){
console.log("setStorage success:",res);
}
})
//从本地获取
wx.getStorage({
key: 'userInfo',
success(res){
//转换成对象
console.log("getStorage success:",JSON.parse(res.data));
that.setData({
userInfo:JSON.parse(res.data)
})
}
})
}
else{
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this;
//从本地获取
wx.getStorage({
key: 'userInfo',
success(res){
//转换成对象
console.log("getStorage success:",JSON.parse(res.data));
that.setData({
userInfo:JSON.parse(res.data)
})
}
})
},
})
三、记录
1.如果不转换成对象
2.注意that的使用