class Store {
storage: Storage;
constructor(storage: Storage) {
this.storage = storage;
}
set(key: string, value: any) {
if (!this.storage) {
return;
}
if (key != null && value != null) {
this.storage.setItem(key, value);
}
}
get(key: string) {
if (!this.storage) {
return null;
}
if (key == null) {
return null;
}
return this.storage.getItem(key);
}
setJSON(key: string, jsonValue: any) {
if (jsonValue != null) {
this.set(key, JSON.stringify(jsonValue));
}
}
getJSON<T>(key: string): T | null {
const value = this.get(key);
if (value != null) {
return JSON.parse(value);
} else {
return null;
}
}
remove(key: string) {
this.storage.removeItem(key);
}
}
/**
* 会话级缓存
*/
export const session = new Store(sessionStorage);
/**
* 本地缓存
*/
export const local = new Store(localStorage);
export default {
session,
local,
};
浏览器存储封装
最新推荐文章于 2024-09-30 15:42:36 发布