90 lines
1.9 KiB
TypeScript
90 lines
1.9 KiB
TypeScript
const sessionCache = {
|
||
set(key: string, value: any) {
|
||
if (!sessionStorage || key == null || value == null) return;
|
||
|
||
try {
|
||
const str = typeof value === 'string' ? value : JSON.stringify(value);
|
||
|
||
// 限制:如果数据超过 1MB,就不存
|
||
if (str.length > 1024 * 1024) {
|
||
console.warn(`sessionStorage.setItem(${key}) 跳过,数据过大(${(str.length / 1024).toFixed(2)} KB)`);
|
||
return;
|
||
}
|
||
|
||
sessionStorage.setItem(key, str);
|
||
} catch (e) {
|
||
console.error(`sessionStorage.setItem(${key}) 失败:`, e);
|
||
}
|
||
},
|
||
|
||
get(key: string) {
|
||
if (!sessionStorage) {
|
||
return null;
|
||
}
|
||
if (key == null) {
|
||
return null;
|
||
}
|
||
return sessionStorage.getItem(key);
|
||
},
|
||
setJSON(key: string, jsonValue: any) {
|
||
if (jsonValue != null) {
|
||
this.set(key, JSON.stringify(jsonValue));
|
||
}
|
||
},
|
||
getJSON(key: string) {
|
||
const value = this.get(key);
|
||
if (value != null) {
|
||
return JSON.parse(value);
|
||
}
|
||
return null;
|
||
},
|
||
remove(key: string) {
|
||
sessionStorage.removeItem(key);
|
||
}
|
||
};
|
||
const localCache = {
|
||
set(key: string, value: any) {
|
||
if (!localStorage) {
|
||
return;
|
||
}
|
||
if (key != null && value != null) {
|
||
localStorage.setItem(key, value);
|
||
}
|
||
},
|
||
get(key: string) {
|
||
if (!localStorage) {
|
||
return null;
|
||
}
|
||
if (key == null) {
|
||
return null;
|
||
}
|
||
return localStorage.getItem(key);
|
||
},
|
||
setJSON(key: string, jsonValue: any) {
|
||
if (jsonValue != null) {
|
||
this.set(key, JSON.stringify(jsonValue));
|
||
}
|
||
},
|
||
getJSON(key: string) {
|
||
const value = this.get(key);
|
||
if (value != null) {
|
||
return JSON.parse(value);
|
||
}
|
||
return null;
|
||
},
|
||
remove(key: string) {
|
||
localStorage.removeItem(key);
|
||
}
|
||
};
|
||
|
||
export default {
|
||
/**
|
||
* 会话级缓存
|
||
*/
|
||
session: sessionCache,
|
||
/**
|
||
* 本地缓存
|
||
*/
|
||
local: localCache
|
||
};
|