小程序缓存封装 storage

复制代码
const postfix = '_expiry' // 缓存有效期后缀   

module.exports = {
  /**  
   * 设置缓存   
   * @param  {[type]} k [键名]  
   * @param  {[type]} v [键值]  
   * @param  {[type]} t [时间、单位秒]  
   */
  set(k, v, t) {
    uni.setStorageSync(k, v)
    const seconds = parseInt(t)
    if (seconds > 0) {
      let timestamp = Date.parse(new Date())
      timestamp = timestamp / 1000 + seconds
      uni.setStorageSync(k + postfix, timestamp + '')
    } else {
      uni.removeStorageSync(k + postfix)
    }
  },

  /**  
   * 获取缓存   
   * @param  {[type]} k   [键名]  
   * @param  {[type]} def [获取为空时默认]  
   */
  get(k, def) {
    const deadtime = parseInt(uni.getStorageSync(k + postfix))
    if (deadtime) {
      if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
        if (def) {
          return def
        } else {
          return false
        }
      }
    }
    const res = uni.getStorageSync(k)
    if (res) {
      return res
    }
    if (def == undefined || def == "") {
      def = false
    }
    return def
  },

  /**
   * 删除指定缓存
   * @param {Object} k
   */
  remove(k) {
    uni.removeStorageSync(k)
    uni.removeStorageSync(k + postfix)
  },

  /**  
   * 清理所有缓存  
   * @return {[type]} [description]  
   */
  clear() {
    uni.clearStorageSync()
  }
}

更多请查看 人间且慢行 | 前端网站大全 | web前端开发

相关推荐
清水白石0088 小时前
Python 如何设计一个线程安全的缓存?从锁策略、LRU 到工程化实战
python·安全·缓存
城管不管9 小时前
MySQL 慢查询完整排查
java·服务器·jvm·数据库·mysql·spring·面试
岁岁种桃花儿9 小时前
Vue核心语法第十一篇:绑定样式
前端·javascript·vue.js
Ai-_Man9 小时前
从AI公式到可编辑文档:MathType格式转换技术分析教程
人工智能·ai·小程序
风流 少年18 小时前
Spring AI 2.0:Memory
java·后端·spring
show43318 小时前
2026视频处理小程序技术选型指南:链接解析+OCR+ASR+AI配音多引擎对比
小程序·ocr·音视频
万少18 小时前
给 DeepSeek Harness 装个"应用商店":一条命令,595 个插件随你逛
前端·javascript·后端
Brown.alexis19 小时前
es6知识点1-自备使用
前端·ecmascript·es6
小爬的老粉丝20 小时前
JavaScript 纯前端预览 WPS:先识别容器,再路由解析器
前端·javascript·wps
Java成神之路-20 小时前
Spring Cloud 微服务契约先行:为什么 Controller 建议要实现 Feign 接口?
spring·spring cloud·微服务