storage.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. interface setParam {
  2. key: string,
  3. data: any,
  4. success?: () => {},
  5. fail?: (err: any) => {}
  6. }
  7. class Storage {
  8. /**
  9. * 设置缓存
  10. * @param param
  11. */
  12. public set(param: setParam) {
  13. try {
  14. window.localStorage.setItem(param.key, JSON.stringify(param.data))
  15. typeof param.success == 'function' && param.success()
  16. } catch (error) {
  17. typeof param.fail == 'function' && param.fail(error)
  18. }
  19. }
  20. /**
  21. * 获取缓存
  22. * @param key
  23. * @returns
  24. */
  25. public get(key: string) {
  26. try {
  27. const json: any = window.localStorage.getItem(key)
  28. return JSON.parse(json)
  29. } catch (error) {
  30. return null
  31. }
  32. }
  33. /**
  34. * 移除指定缓存
  35. * @param key
  36. */
  37. public remove(key: string | string[]) {
  38. if (typeof key == 'string') window.localStorage.removeItem(key)
  39. else key.forEach(item => { window.localStorage.removeItem(item) })
  40. }
  41. /**
  42. * 清理缓存
  43. */
  44. public clear() {
  45. window.localStorage.clear()
  46. }
  47. }
  48. const storage = new Storage()
  49. export default storage