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

相关推荐
编程牛马姐5 小时前
独立站SEO流量增长:提高Google排名的优化方法
前端·javascript·网络
ego.iblacat7 小时前
Redis 核心概念与部署
数据库·redis·缓存
万岳科技系统开发7 小时前
商城系统搭建自建平台与入驻第三方平台对比分析
数据库·小程序·架构
云烟成雨TD7 小时前
Spring AI Alibaba 1.x 系列【23】短期记忆
java·人工智能·spring
妮妮喔妮8 小时前
supabase的webhook报错
开发语言·前端·javascript
河阿里8 小时前
SpringBoot :使用 @Configuration 集中管理 Bean
java·spring boot·spring
Flittly8 小时前
【SpringSecurity新手村系列】(4)验证码功能实现
java·spring boot·安全·spring
Flittly8 小时前
【SpringSecurity新手村系列】(3)自定义登录页与表单认证
java·笔记·安全·spring·springboot
qq_12084093718 小时前
Three.js 大场景分块加载实战:从全量渲染到可视集调度
开发语言·javascript·数码相机
苏渡苇9 小时前
5 分钟跑起 Redis(Docker 版)
数据库·redis·缓存·docker·redis入门