const postfix = '_cache_time'; // 缓存前缀 const simpleCache = { postfix: postfix, } /** * 写入缓存 * @param {String} key 本地缓存中的指定的key * @param {Any} data 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象 * @param {Number} time 保存的时间, 数字类型,单位秒 为空则永久有效. */ simpleCache.put = function(key, data, time) { uni.setStorageSync(key, data) var seconds = parseInt(time); if (seconds > 0) { var timestamp = Date.parse(new Date()); timestamp = timestamp / 1000 + seconds; uni.setStorageSync(key + postfix, timestamp + "") } else { uni.removeStorageSync(key + postfix) } } /** * 从本地缓存中同步获取指定 key 对应的内容。 * @param {String} key 本地缓存中的指定的 key * @param def 获取失败时的默认内容,可以为空. */ simpleCache.get = function(key, def) { var deadtime = parseInt(uni.getStorageSync(key + postfix)) if (deadtime) { if (parseInt(deadtime) < Date.parse(new Date()) / 1000) { //已过期 if (def) { return def; } else { //清除过期时间 uni.removeStorageSync(key + postfix) //移除缓存 uni.removeStorageSync(key) return false; } } } var res = uni.getStorageSync(key); if (res) { return res; } else { if (def == undefined || def == "") { def = false; uni.removeStorageSync(key) } return def; } } /** * 从本地缓存中同步移除指定 key。 * @param {String} key 本地缓存中的指定的 key */ simpleCache.remove = function(key) { uni.removeStorageSync(key); uni.removeStorageSync(key + postfix); } /** * 同步清理本地数据缓存。 */ simpleCache.clear = function() { // 这里面其实可以扩展你不想清理的缓存,比如你保存的用户登录状态. 在清理之前先获取一次. // var user = simpleCache.get("user_info"); uni.clearStorageSync(); // simpleCache.put("user_info",user); // 等 其它的自行扩展. } /** * id_key:存储的key * image_url:图片路径 * isError:是否加载错误 * time:缓存时间 */ simpleCache.image_cache=function(id_key,image_url,isError,time=3*24*60*60) { let imgTemp= simpleCache.get(id_key) if(!imgTemp){ //本地没有缓存,需要下载 uni.downloadFile({ url: image_url, success: (res) => { if (res.statusCode === 200) { let temp=res.tempFilePath simpleCache.put(id_key,temp,time) } } }); return image_url }else{ if(isError){ console.log("缓存的图片发生错误了,从网络中获取",image_url) return image_url }else{ console.log("缓存的图片没有发生错误,从缓存中获取") return imgTemp } } } // export default simpleCache module.exports = { put:simpleCache.put, get:simpleCache.get, remove:simpleCache.remove, clear:simpleCache.clear, cacheImg:simpleCache.image_cache }