const getCache = function (key: string) {
    let value: string | null = localStorage.getItem(key);
    if (value != null) {
        let cache: CacheModel;
        cache = JSON.parse(value) as CacheModel
        let timestamp: number = (new Date()).valueOf() / 1000;
        if (cache.time < timestamp) {
            clearCacheByKey(key)
            return null;
        }
        return cache.data
    } else {
        return null;
    }
}
const setCache = function (key: string, obj: object | string, time: number = 3600) {
    let timestamp: number = (new Date()).valueOf() / 1000;
    let cache: CacheModel = {
        data: obj,
        time: timestamp + time
    }
    localStorage.setItem(key, JSON.stringify(cache))
}
const clearCache = function () {
    localStorage.clear();
}
const clearCacheByKey = function (key: string) {
    localStorage.removeItem(key)
}
interface CacheModel {
    data: object | string,
    time: number
}
export { getCache, setCache, clearCache, clearCacheByKey }


主要就是这么几个方法


getCache(key) 更具key 返回缓存数据,如果过期,会清除缓存!


setCache(key,value,3600) 设置缓存key value 时间是秒开始的(可不填)。


clearCache() 清除所有缓存


clearCacheByKey(key) 清除key的缓存