storage.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. }