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 自定義緩存機制
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 介紹 3.0 項目重寫了~~基于uni-app,colorUI,封裝了《自定義TabBar》《上傳圖片》《全局自定...
- 介紹 uni-app自帶的底部導(dǎo)航欄雖然也很好用,但是遇到中間需要有一個自定義按鈕的需求的時候如果使用自帶的mid...
- 記錄下 自己花了一上午時間做的 UNIAPP 自定義 loading自定義 toast 同理 只是給組件傳個參數(shù)過...