封装Storage工具

43 阅读1分钟
class Cache {
  constructor(isLocal = true) {
    this.storage = isLocal ? localStorage : sessionStorage
  }

  setCache(key, value) {
    if (!value) {
      throw new Error('value error: value 必须有值')
    }
    if (value) {
      // localStorage本身是不能直接存储对象类型
      localStorage.setItem(key, JSON.stringify(value))
    }
  }

  getCache(key) {
    const result = this.storage.getItem(key)
    if (result) {
      return JSON.parse(result)
    }
  }

  removeCache(key) {
    this.storage.removeItem(key)
  }

  clearCache(key) {
    this.storage.clear()
  }
}

const localCache = new Cache()
const sessionCache = new Cache(false)

// 封装过后可以直接存
const info = {
  name:'www',
  age:19
}
sessionCache.setCache('info',info)
localCache.getCache(info)