小技巧1 | 封装Storage-Cache存储工具

235 阅读1分钟

新建cache.js

class Cache {
  constructor(isLocal=true){
    isLocal?this.Storage=localStorage:sessionStorage
  }
  setCache(key, value) {
    if (value) this.Storage.setItem(key, JSON.stringify(value));
    else {
      throw new Error("value必须有值");
    }
  }
  getCache(key) {
    const cacheRes = JSON.parse(this.Storage.getItem(key));
    if (cacheRes) return cacheRes;
    else throw new Error("getCache返回失败");
  }
  removeCache(key) {
    this.Storage.removeItem(key);
  }
  clearCache() {
    this.Storage.clear();
  }
  getCacheLength() {
    return this.Storage.length;
  }

  getKeyCache(index) {
    const cacheRes = JSON.parse(this.Storage.key(index));
    if (cacheRes) return cacheRes;
    else throw new Error("getCache返回失败");
  }
}
const localCache = new Cache();
const sessionCache=new Cache(false);