单一的localStorage封装
class Cache {
setCache(key: string, value: any) {
if (value) {
localStorage.setItem(key, JSON.stringify(value))
}
}
getCache(key: string) {
const value = localStorage.getItem(key)
if (value) {
return JSON.parse(value)
}
}
removeCache(key: string) {
localStorage.removeItem(key)
}
clear() {
localStorage.clear()
}
}
export default new Cache()
对localStorage、sessionStorage同时进行封装
enum CacheType {
Local,
Session
}
class Cache {
storage: Storage
constructor(type: CacheType) {
this.storage = type === CacheType.Local ? localStorage : sessionStorage
}
setCache(key: string, value: any) {
if (value) {
this.storage.setItem(key, JSON.stringify(value))
}
}
getCache(key: string) {
const value = this.storage.getItem(key)
if (value) {
return JSON.parse(value)
}
}
removeCache(key: string) {
this.storage.removeItem(key)
}
clear() {
this.storage.clear()
}
}
const localCache = new Cache(CacheType.Local)
const sessionCache = new Cache(CacheType.Session)
export { localCache, sessionCache }