searchs.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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
  35. ? delete this.searchs[this.key][type]
  36. : delete this.searchs[this.key];
  37. this.save();
  38. }
  39. return this.searchs;
  40. }
  41. getSearchs() {
  42. return this.searchs;
  43. }
  44. removeByKey(key: string) {
  45. console.log('真正的删', key);
  46. delete this.searchs[key];
  47. this.save();
  48. return this.searchs;
  49. }
  50. removeAll() {
  51. this.searchs = {};
  52. localStorage.setItem(this.saveKey, JSON.stringify(this.searchs));
  53. return this.searchs;
  54. }
  55. removeByRouter(path: string) {
  56. this.searchs = this.parse();
  57. for (const key in this.searchs) {
  58. // console.log('清除的循环', key, this.searchs[key]?.bind)
  59. if (path === key || path === this.searchs[key]?.bind) {
  60. console.log('清除的页面', key);
  61. this.removeByKey(key);
  62. }
  63. }
  64. }
  65. removeByOtherRouter(path: string) {
  66. this.searchs = this.parse();
  67. for (const key in this.searchs) {
  68. if (path === key || path === this.searchs[key]?.bind) {
  69. } else {
  70. this.removeByKey(key);
  71. }
  72. }
  73. }
  74. update(data: any, key: string | any, type: 'page' | 'form' | 'bind' | '') {
  75. this.searchs = this.parse();
  76. const k = key || this.key;
  77. if (!this.searchs[k]) {
  78. this.searchs[k] = { ...initSearch };
  79. }
  80. if (type) {
  81. this.searchs[k][type] = data;
  82. } else {
  83. this.searchs[k] = data;
  84. }
  85. this.save();
  86. return this.searchs;
  87. }
  88. }
  89. const initSearch = {
  90. form: {},
  91. page: {}
  92. };