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

相关推荐
名字还没想好☜4 小时前
React 实现暗黑模式切换:localStorage 持久化、SSR 首屏闪烁与跟随系统主题
前端·javascript·react.js·ecmascript·react·next.js
数商云企4 小时前
2026年陕西软件开发首选数商云企AI微入口小程序定制方案
人工智能·小程序
梁云亮4 小时前
spring整合Junit4
spring
自动化监测Learner4 小时前
主流 Web 端地图引擎对比:选型指南与优劣分析
javascript
那个松鼠很眼熟w7 小时前
4.Spring-Ai入门案例
java·人工智能·spring
宿6749 小时前
vue3-config
前端·javascript·vue.js
抠脚小弟10 小时前
Spring Cache 使用详解:从入门到实战
java·spring
bug总结10 小时前
uniapp 微信小程序分包规范
微信小程序·小程序·uni-app
Quor11 小时前
小程序工作室:AI 生成即运行的可视化工作台
人工智能·小程序
ShineWinsu11 小时前
对于 Vue 3:从为什么学 Vue,到声明式渲染与数据响应式的解析
前端·javascript·vue.js