storage.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import Cookies from 'js-cookie';
  2. /**
  3. * window.localStorage 浏览器永久缓存
  4. * @method set 设置永久缓存
  5. * @method get 获取永久缓存
  6. * @method remove 移除永久缓存
  7. * @method clear 移除全部永久缓存
  8. */
  9. export const Local = {
  10. // 查看 v2.4.3版本更新日志
  11. setKey(key: string) {
  12. // @ts-ignore
  13. return `${__NEXT_NAME__}:${key}`;
  14. },
  15. // 设置永久缓存
  16. set<T>(key: string, val: T) {
  17. window.localStorage.setItem(Local.setKey(key), JSON.stringify(val));
  18. },
  19. // 获取永久缓存
  20. get(key: string) {
  21. let json = <string>window.localStorage.getItem(Local.setKey(key));
  22. return JSON.parse(json);
  23. },
  24. // 移除永久缓存
  25. remove(key: string) {
  26. window.localStorage.removeItem(Local.setKey(key));
  27. },
  28. // 移除全部永久缓存
  29. clear() {
  30. window.localStorage.clear();
  31. },
  32. };
  33. /**
  34. * window.sessionStorage 浏览器临时缓存
  35. * @method set 设置临时缓存
  36. * @method get 获取临时缓存
  37. * @method remove 移除临时缓存
  38. * @method clear 移除全部临时缓存
  39. */
  40. export const Session = {
  41. // 设置临时缓存
  42. set<T>(key: string, val: T) {
  43. if (key === 'token') return Cookies.set(key, val);
  44. window.sessionStorage.setItem(Local.setKey(key), JSON.stringify(val));
  45. },
  46. // 获取临时缓存
  47. get(key: string) {
  48. if (key === 'token') return Cookies.get(key);
  49. let json = <string>window.sessionStorage.getItem(Local.setKey(key));
  50. return JSON.parse(json);
  51. },
  52. // 移除临时缓存
  53. remove(key: string) {
  54. if (key === 'token') return Cookies.remove(key);
  55. window.sessionStorage.removeItem(Local.setKey(key));
  56. },
  57. // 移除全部临时缓存
  58. clear() {
  59. Cookies.remove('token');
  60. window.sessionStorage.clear();
  61. },
  62. };