const cacheMap = new Map()
let timeoutDefault = 1200
function isTimeout(name: string) {
const data = cacheMap.get(name)
if (!data) return true
if (data.timeout === 0) return false
const currentTime = Date.now()
const overTime = (currentTime - data.createTime) / 1000
if (overTime > data.timeout) {
cacheMap.delete(name)
if (name.startsWith('_')) {
try {
uni.removeStorageSync(name)
} catch (e) {
console.log(e)
}
}
return true
}
return false
}
class CacheCell {
private data: any
private timeout: number
private createTime: number
constructor(data: any, timeout: number) {
this.data = data
this.timeout = timeout
this.createTime = Date.now()
}
}
class MinCache {
constructor(timeout = timeoutDefault) {
try {
const res = uni.getStorageInfoSync()
res.keys.forEach((name) => {
try {
const value = uni.getStorageSync(name)
cacheMap.set(name, value)
} catch (e) {
console.log(e)
}
})
} catch (e) {
console.log(e)
}
timeoutDefault = timeout
}
set(name: string, data: any, timeout = timeoutDefault) {
const cachecell = new CacheCell(data, timeout)
let cache = null
// if (name.startsWith('_')) {
try {
uni.setStorageSync(name, cachecell)
cache = cacheMap.set(name, cachecell)
} catch (e) {
console.log(e)
}
// } else {
// cache = cacheMap.set(name, cachecell)
// }
return cache
}
get(name: string) {
return isTimeout(name) ? null : cacheMap.get(name).data
}
delete(name: string) {
let value = false
if (name.startsWith('_')) {
try {
uni.removeStorageSync(name)
value = cacheMap.delete(name)
} catch (e) {
console.log(e)
}
} else {
value = cacheMap.delete(name)
}
return value
}
has(name: string) {
return !isTimeout(name)
}
clear() {
let value = false
try {
uni.clearStorageSync()
cacheMap.clear()
value = true
} catch (e) {
console.log(e)
}
return value
}
}
export const minCache = new MinCache()
uni-app 自定义缓存机制
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 介绍 3.0 项目重写了~~基于uni-app,colorUI,封装了《自定义TabBar》《上传图片》《全局自定...
- 介绍 uni-app自带的底部导航栏虽然也很好用,但是遇到中间需要有一个自定义按钮的需求的时候如果使用自带的mid...
- 记录下 自己花了一上午时间做的 UNIAPP 自定义 loading自定义 toast 同理 只是给组件传个参数过...