storage.ts 2.2 KB

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