结合ts封装storeage
在项目中,如果使用原生未封装的localStorage会略显的麻烦。emm,对会话以及本地存储方案进行了二次封装。便于项目的使用。存取对象时都会更加方便,且可以在取对象的时候,拿到对象的类型。
export class LocalCache {
setCache<T = any>(key: string, value: T): boolean;
setCache<T = any>(
key: string,
value: T,
localOrSessionStorage: boolean
): boolean;
setCache<T = any>(
key: string,
value: T,
localOrSessionStorage = true
): boolean {
try {
const val = JSON.stringify(value);
if (localOrSessionStorage) {
window.localStorage.setItem(key, val);
} else {
window.sessionStorage.setItem(key, val);
}
} catch (error) {
return false;
}
return true;
}
getCache<T = any>(key: string): T;
getCache<T = any>(key: string, localOrSessionStorage: boolean): T;
getCache<T>(key: string, localOrSessionStorage = true): T {
let res: any;
if (localOrSessionStorage) {
const val = window.localStorage.getItem(key);
if (val) {
res = JSON.parse(val);
}
}
const val = window.sessionStorage.getItem(key);
if (val) {
res = JSON.parse(val);
}
return res as T;
}
deleteCache(key: string): void;
deleteCache(key: string, localOrSessionStorage: boolean): void;
deleteCache(key: string, localOrSessionStorage = true): void {
if (localOrSessionStorage) window.localStorage.removeItem(key);
else window.sessionStorage.removeItem(key);
}
clearCache(): void;
clearCache(localOrSessionStorage: boolean): void;
clearCache(localOrSessionStorage = true): void {
if (localOrSessionStorage) window.localStorage.clear();
else window.sessionStorage.clear();
}
}
export default new LocalCache();
|