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

相关推荐
_waylau4 小时前
Spring AI开发从入门到实践-Spring AI的应用场景与未来展望
java·人工智能·后端·spring·llm·spring ai
会编程的吕洞宾4 小时前
Spring AI 多轮对话总失忆?ChatMemory 持久化实战
java·人工智能·经验分享·后端·spring
阮靓仔4 小时前
【Spring Boot】Spring Boot 集成 Caffeine 缓存
spring boot·后端·缓存
Yetian_20004 小时前
Spring MVC常用注解整理
java·spring·mvc
少年的范儿4 小时前
React Native + Expo 实战 14|管理远端列表:缓存、刷新与分页
react native·react.js·缓存
少年的范儿4 小时前
React Native + Expo 实战 13|实现登录:会话恢复、过期处理与账号隔离
javascript·react native·react.js
源码手记6 小时前
基于微信小程序的个性化音乐推荐系统-毕设源码
微信小程序·小程序·课程设计
FYKJ_20106 小时前
springboot高校实验室综合管理系统86531-计算机毕业设计、课程设计
java·vue.js·spring boot·后端·python·spring·课程设计
Shimeri7 小时前
基于osc开发的魔法网课助手
javascript·tampermonkey·用户脚本
洋不写bug14 小时前
Spring IoC & DI 超详细解析
spring·di·javaee·spring ioc·类注解·方法注解·扫描路径