小程序缓存封装 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前端开发

相关推荐
鸣弦artha12 小时前
Flutter框架跨平台鸿蒙开发——Build流程深度解析
开发语言·javascript·flutter
想用offer打牌13 小时前
Spring AI Alibaba与 Agent Scope到底选哪个?
java·人工智能·spring
crossaspeed13 小时前
Java-SpringBoot的启动流程(八股)
java·spring boot·spring
lpfasd12314 小时前
springcloud docker 部署问题排查与解决方案
spring·spring cloud·docker
qqqahhh14 小时前
xml文件的动态化配置,导入
xml·spring·springboot
BullSmall14 小时前
SEDA (Staged Event-Driven Architecture, 分阶段事件驱动架构
java·spring·架构
LongJ_Sir15 小时前
Cesium--可拖拽气泡弹窗(Vue3版)
javascript
跟着珅聪学java15 小时前
JavaScript 中定义全局变量的教程
javascript
午安~婉16 小时前
整理知识点
前端·javascript·vue
向前V16 小时前
Flutter for OpenHarmony数独游戏App实战:底部导航栏
javascript·flutter·游戏