基于localStorage封装带过期限制的缓存功能模块

5 篇文章 0 订阅

每个项目中都很有可能使用到本地缓存来处理逻辑,这里基于window.localStorage封装了带过期限制的缓存功能模块。

使用方式:

  import cache from '@/utils/cache.js'   // 根据项目目录而定

let data = {
    name: 'Justicky',
    work: 'front end'
}

1、设置缓存数据:

cache.set('myInfo', data, 4 * 60 * 60)   // 缓存有效期4小时

2、获取缓存数据:

cache.get('myInfo') // 若已过期返回false,没过期返回相应数据

3、移除一个缓存数据:

cache.remove('myInfo') // 若操作失败返回false,否则为true

4、清空所有缓存数据:

cache.clear() // 若操作失败返回false,否则为true

 

  cache.js文件如下:

/**
 * localStorage 本地缓存功能
 */
class Cache {
  prefix = 'app-name' // 项目前缀,根据不同项目而定
  expires = 4 * 60 * 60 // 默认四小时后失效
  /**
   * [constructor description]
   * @param  {String} prefix  项目前缀
   * @param  {Number} expires 默认缓存时间单位秒
   * @return {[type]}         [description]
   */
  constructor (prefix, expires) {
    if (prefix) {
      this.prefix = prefix.toString()
    }
    if (expires) {
      this.expires = parseInt(expires, 10)
    }
  }

  /**
   * 设置缓存
   * @param key           缓存名
   * @param value         缓存值
   * @param expires       缓存有效时间
   * @returns {boolean}   成功:true, 失败:false
   */
  set (key, value, expires) {
    // 非法缓存名过滤
    if (key === undefined || key === '' || typeof key === 'object') {
      console.error('设置的缓存名不合法!')
      return false
    }

    // 非法缓存时间过滤
    if (!expires || typeof expires !== 'number') {
      console.error('设置缓存过期时间不合法,已使用默认缓存时间!')
      expires = this.expires
    } else {
      expires = parseInt(expires, 10)
    }

    // localStorage中存储数据的键值
    let cacheName = this.prefix + '-[' + key.toString() + ']'
    // 获取过期到秒的时间戳
    let expiresTime = Date.parse(new Date()) / 1000 + expires
    // 初始化存储数据
    const data = {
      type: typeof value,
      value: value,
      expires: expiresTime
    }

    // 存入localStorage
    try {
      window.localStorage.setItem(cacheName, JSON.stringify(data))
      return true
    } catch (err) {
      console.error('存储失败:' + JSON.stringify(err))
      return false
    }
  }

  /**
   * 读取缓存内容
   * @param key
   * @returns {*}
   */
  get (key) {
    // 获取当前到秒的时间戳,用于判断是否过期
    let currentTime = Date.parse(new Date()) / 1000

    // 非法缓存名过滤
    if (key === undefined || key === '' || typeof key === 'object') {
      console.error('读取的缓存名不合法!')
      return false
    }

    // 获取localStorage中要读取的缓存名
    let cacheName = this.prefix + '-[' + key.toString() + ']'
    try {
      const cacheData = JSON.parse(window.localStorage.getItem(cacheName))
      // 判断判断缓存是否过期
      if (cacheData.expires < currentTime) {
        console.error('读取的缓存数据已过期!')
        return false
      }
      return cacheData.value
    } catch (err) {
      console.error('读取数据失败:' + JSON.stringify(err))
      return false
    }
  }

  /**
   * 移除一个缓存
   * @param key
   * @returns {boolean}
   */
  remove (key) {
    // 非法缓存名过滤
    if (key === undefined || key === '' || typeof key === 'object') {
      console.error('移除的缓存名不合法!')
      return false
    }
    let cacheName = this.prefix + '-[' + key.toString() + ']'
    try {
      window.localStorage.removeItem(cacheName)
      return true
    } catch (err) {
      console.error('移除指定缓存数据失败:' + JSON.stringify(err))
      return false
    }
  }

  /**
   * 清空所有缓存数据
   */
  clear () {
    try {
      window.localStorage.clear()
      return true
    } catch (err) {
      console.error('清空所有缓存数据失败:' + JSON.stringify(err))
      return false
    }
  }
}

const _this = new Cache()
export default _this

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值