cache.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const sessionCache = {
  2. set(key: string, value: any) {
  3. if (!sessionStorage) {
  4. return;
  5. }
  6. if (key != null && value != null) {
  7. sessionStorage.setItem(key, value);
  8. }
  9. },
  10. get(key: string) {
  11. if (!sessionStorage) {
  12. return null;
  13. }
  14. if (key == null) {
  15. return null;
  16. }
  17. return sessionStorage.getItem(key);
  18. },
  19. setJSON(key: string, jsonValue: any) {
  20. if (jsonValue != null) {
  21. this.set(key, JSON.stringify(jsonValue));
  22. }
  23. },
  24. getJSON(key: string) {
  25. const value = this.get(key);
  26. if (value != null) {
  27. return JSON.parse(value);
  28. }
  29. },
  30. remove(key: string) {
  31. sessionStorage.removeItem(key);
  32. }
  33. };
  34. const localCache = {
  35. set(key: string, value: any) {
  36. if (!localStorage) {
  37. return;
  38. }
  39. if (key != null && value != null) {
  40. localStorage.setItem(key, value);
  41. }
  42. },
  43. get(key: string) {
  44. if (!localStorage) {
  45. return null;
  46. }
  47. if (key == null) {
  48. return null;
  49. }
  50. return localStorage.getItem(key);
  51. },
  52. setJSON(key: string, jsonValue: any) {
  53. if (jsonValue != null) {
  54. this.set(key, JSON.stringify(jsonValue));
  55. }
  56. },
  57. getJSON(key: string) {
  58. const value = this.get(key);
  59. if (value != null) {
  60. return JSON.parse(value);
  61. }
  62. },
  63. remove(key: string) {
  64. localStorage.removeItem(key);
  65. }
  66. };
  67. export default {
  68. /**
  69. * 会话级缓存
  70. */
  71. session: sessionCache,
  72. /**
  73. * 本地缓存
  74. */
  75. local: localCache
  76. };