基于localStorage封装一个可设置有效期的Storage类

将数据存储在localStorage中,封装一个Storage类——NBStorage,通过在key前设置前缀的方式来区分NBStorage存入的数据和其他方式存入的数据。

class NBStorage {
  constructor() {
    // 需要存入的数据的前缀
    this.PREFIX = 'NBS_';
    // 记录数据过期时间的前缀
    this.EXPIRES_PREFIX = this.PREFIX + 'EXPIRES_'
    // 初始化时清理过期数据
    this._checkAll();
  }

  // 遍历所有带前缀的数据
  _checkAll() {
    // localStorage可以当做一个对象直接用for...in 遍历,学到了
    for (let k in localStorage) {
      // 使用string.includes('str')的方法判断string中是否包含'str'字段
      if (k.includes(this.EXPIRES_PREFIX)) {
        this._checkItem(k.replace(this.EXPIRES_PREFIX, ''));
      }
    }
  }

  _checkItem(key) {
    // 参数的key为用户输入的key值,直接在localStorage里是检索不到的,需要加前缀
    const targetKey = this._getTargetKey(key);
    const expiresKey = this._getExpiresKey(key);
    // 在localStorage检索加前缀后的key值
    const expires = localStorage.getItem(expiresKey);
    const now = Date.now()
    // 检测是否过期,删除过期数据以及其expires
    if (now > +expires) {
      localStorage.removeItem(targetKey)
      localStorage.removeItem(expiresKey)
    }
  }

  // 给存入数据key加前缀
  _getTargetKey(key) {
    return this.PREFIX + key
  }

  // 给存入过期时间key加前缀
  _getExpiresKey(key) {
    return this.EXPIRES_PREFIX + key
  }
  
  getItem(key) {
  // 清理过期数据是在初始化以及获取数据时进行的,只要保证用户获取不到过期数据即可
    this._checkItem(key)
    const targetKey = this._getTargetKey(key);
  // 检索数据
    return localStorage.getItem(targetKey);
  }

  setItem(key, value, expires = 0) {
    const targetKey = this._getTargetKey(key);
    const expiresKey = this._getExpiresKey(key);
    localStorage.setItem(targetKey, value)
    // 添加过期时间
    localStorage.setItem(expiresKey, Date.now() + expires + '');
  }

  removeItem(key) {
    const targetKey = this._getTargetKey(key);
    const expiresKey = this._getExpiresKey(key);
    localStorage.removeItem(targetKey)
    localStorage.removeItem(expiresKey);
  }

  // clear不能直接调用localStorage的clear,只需要清理带有前缀的数据,因此直接遍历,一个一个清除
  clear() {
    for (let k in localStorage) {
      if (k.includes(this.PREFIX) || k.includes(this.EXPIRES_PREFIX)) {
        localStorage.removeItem(k)
      }
    }
  }
}
export default NBStorage

总结:

1、单独封装一个类能有效避免复杂页面开发时localStorage冲突问题

2、之前做项目时使用localStorage都是使用对象转成JSON再存入取出,这样每次数据更新都非常复杂。localStorage是可以作为对象遍历的,将数据通过键值对的方式直接存入localStorage,通过前缀即可分辨是否为需要的数据,过期时间设置为类似名字的属性,数据操作更加简单,值得学习!

可提升的地方:

1、NBStorage作为一个通用类,有可能需要在项目的不同位置使用,存取不同类型的数据,因此可设置一个前缀名的参数,通过二次封装在项目的不同位置进行使用,同时进行数据隔离。

2、对于敏感数据(或所有数据)进行加密

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值