storage.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { JSONStringify, JSONParse } from './utils'
  2. /**
  3. * * 存储本地会话数据
  4. * @param k 键名
  5. * @param v 键值(无需stringiiy)
  6. * @returns RemovableRef
  7. */
  8. export const setLocalStorage = <T>(k: string, v: T) => {
  9. try {
  10. window.localStorage.setItem(k, JSONStringify(v))
  11. } catch (error) {
  12. return false
  13. }
  14. }
  15. /**
  16. * * 获取本地会话数据
  17. * @param k 键名
  18. * @returns any
  19. */
  20. export const getLocalStorage = (k: string) => {
  21. const item = window.localStorage.getItem(k)
  22. try {
  23. return item ? JSONParse(item) : item
  24. } catch (err) {
  25. return item
  26. }
  27. }
  28. /**
  29. * * 清除本地会话数据
  30. * @param name
  31. */
  32. export const clearLocalStorage = (name: string) => {
  33. window.localStorage.removeItem(name)
  34. }
  35. /**
  36. * * 存储临时会话数据
  37. * @param k 键名
  38. * @param v 键值
  39. * @returns RemovableRef
  40. */
  41. export const setSessionStorage = <T>(k: string, v: T) => {
  42. try {
  43. window.sessionStorage.setItem(k, JSON.stringify(v))
  44. } catch (error) {
  45. return false
  46. }
  47. }
  48. /**
  49. * * 获取临时会话数据
  50. * @returns any
  51. */
  52. export const getSessionStorage: (k: string) => any = (k: string) => {
  53. const item = window.sessionStorage.getItem(k)
  54. try {
  55. return item ? JSON.parse(item) : item
  56. } catch (err) {
  57. return item
  58. }
  59. }
  60. /**
  61. * * 清除本地会话数据
  62. * @param name
  63. */
  64. export const clearSessioStorage = (name: string) => {
  65. window.sessionStorage.removeItem(name)
  66. }
  67. /**
  68. * * 设置 cookie
  69. * @param name 键名
  70. * @param cvalue 键值
  71. * @param exdays 过期时间
  72. */
  73. export const setCookie = (name: string, cvalue: string, exdays: number) => {
  74. const d = new Date();
  75. d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  76. const expires = "expires=" + d.toUTCString();
  77. document.cookie = name + "=" + cvalue + "; " + expires;
  78. }
  79. /**
  80. * * 获取 cookie
  81. * @param cname 键名
  82. * @returns string
  83. */
  84. export const getCookie = (cname: string) => {
  85. const name = cname + "=";
  86. const ca = document.cookie.split(';');
  87. for (let i = 0; i < ca.length; i++) {
  88. let c = ca[i];
  89. while (c.charAt(0) == ' ') c = c.substring(1);
  90. if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
  91. }
  92. return "";
  93. }
  94. /**
  95. * * 清除 cookie
  96. * @param name 键名
  97. * @returns string
  98. */
  99. export const clearCookie = (name: string) => {
  100. setCookie(name, "", -1);
  101. }