searchs.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /* eslint-disable no-empty */
  2. export class Searchs {
  3. saveKey = 'searchs'
  4. initSearch = {
  5. form: {},
  6. page: {}
  7. }
  8. searchs = {} as any
  9. key = '' as string
  10. constructor(key: string) {
  11. this.key = key
  12. this.searchs = this.parse()
  13. }
  14. save() {
  15. localStorage.setItem(this.saveKey, JSON.stringify(this.searchs))
  16. }
  17. parse() {
  18. let json = { ...initSearch }
  19. try {
  20. const val = localStorage.getItem(this.saveKey) as string
  21. json = JSON.parse(val) || json
  22. } catch (error) {}
  23. return json
  24. }
  25. get(key: string) {
  26. const k = key || this.key
  27. if (!this.searchs[k]) {
  28. this.searchs[k] = { ...initSearch }
  29. }
  30. return this.searchs[k]
  31. }
  32. remove(type: 'page' | 'form') {
  33. if (this.searchs && this.searchs[this.key]) {
  34. type ? delete this.searchs[this.key][type] : delete this.searchs[this.key]
  35. this.save()
  36. }
  37. return this.searchs
  38. }
  39. getSearchs() {
  40. return this.searchs
  41. }
  42. removeByKey(key: string) {
  43. console.log('真正的删', key)
  44. delete this.searchs[key]
  45. this.save()
  46. return this.searchs
  47. }
  48. removeAll() {
  49. this.searchs = {}
  50. localStorage.setItem(this.saveKey, JSON.stringify(this.searchs))
  51. return this.searchs
  52. }
  53. removeByRouter(path: string) {
  54. this.searchs = this.parse()
  55. for (let key in this.searchs) {
  56. // console.log('清除的循环', key, this.searchs[key]?.bind)
  57. if (path === key || path === this.searchs[key]?.bind) {
  58. console.log('清除的页面', key)
  59. this.removeByKey(key)
  60. }
  61. }
  62. }
  63. removeByOtherRouter(path: string) {
  64. this.searchs = this.parse()
  65. for (let key in this.searchs) {
  66. if (path === key || path === this.searchs[key]?.bind) {
  67. } else {
  68. this.removeByKey(key)
  69. }
  70. }
  71. }
  72. update(data: any, key: string | any, type: 'page' | 'form' | 'bind' | '') {
  73. this.searchs = this.parse()
  74. const k = key || this.key
  75. if (!this.searchs[k]) {
  76. this.searchs[k] = { ...initSearch }
  77. }
  78. if (type) {
  79. this.searchs[k][type] = data
  80. } else {
  81. this.searchs[k] = data
  82. }
  83. this.save()
  84. return this.searchs
  85. }
  86. }
  87. const initSearch = {
  88. form: {},
  89. page: {}
  90. }