企业网站关于我们,如何免费查询企业信息,建工类培训机构,wordpress 分类归档1、定义CacheManage类#xff0c;有set和get方法
class CacheManage {set() {},get() {}
}set用来设置缓存#xff0c;get用来获取缓存
2、完善set业务逻辑
大概逻辑如下#xff1a; 1、将接收params参数#xff0c;包含key、data、unit、time key 缓存字段#xff0c;…1、定义CacheManage类有set和get方法
class CacheManage {set() {},get() {}
}set用来设置缓存get用来获取缓存
2、完善set业务逻辑
大概逻辑如下 1、将接收params参数包含key、data、unit、time key 缓存字段必填 data 缓存数据必填 unit 缓存时间单位有效值 day hours minutes; 默认 day time 缓存有效期默认 0 (无过期时间) 2、判断key和data不能为空防止设置缓存时出错 3、判断unit参数分别处理缓存过期时间 4、判断缓存size是否超上限并及时清除 5、设置缓存并以’|字符分割过期时间戳 6、实现代码如下 set(params) {let { key, data, unitday, time0 } params// 过期时间let expirationTime 0if (key data) {let storageInfo uni.getStorageInfoSync()if(storageInfo.limitSize - storageInfo.currentSize 5) {uni.clearStorageSync()}if(time 0) { // 缓存不会失效uni.setStorageSync(key, data)// uni.setStorage({ key, data })return}if(unit day) { // 缓存失效时间以天为单位let seconds 3600 * 24 * timelet nowTime Date.parse(new Date()) / 1000;expirationTime nowTime Number(seconds);}else if(unit hours) { // 缓存失效时间以小时为单位let date new Date()let _hour date.getHours()date.setHours(_hour time)expirationTime Date.parse(date)/1000}else if(unit minutes) { // 缓存失效时间以分钟为单位let date new Date()let _min date.getMinutes()date.setMinutes(_mintime)expirationTime Date.parse(date)/1000}uni.setStorageSync(key, JSON.stringify(data) | expirationTime)}}3、完善get逻辑
大概逻辑如下 1、将接收要获取的缓存key 2、判断key不能为空 3、获取缓存 4、获取当前的时间戳与缓存时间错比较以判断缓存是否过期 5、获取指定缓存key判断数据类型分别返回 实现代码如下
get(key) {if (key) {let nowTime Date.parse(new Date()) / 1000;let data uni.getStorageSync(key);if (data) {if(typeof(data) string) {let temp data.split(|)if (temp[1] temp[1] nowTime) {// 缓存已过期删除缓存数据uni.removeStorageSync(key)return ;} else {// 处理有效缓存数据if(temp[1]) {return JSON.parse(temp[0]);}else {return temp[0];}}}else {// 如果不是字符串直接返回return data}}return ;}
}4、导出类
export default new CacheManage()如果觉得有用随手点个赞吧谢谢 关注我不定时分享技术干货~