base.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import {
  2. getStorage,
  3. setStorage,
  4. removeStorage
  5. } from '../utils/index.js'
  6. class base {
  7. constructor() {
  8. this.storageKey = '';
  9. this.storageInfo = {};
  10. this.defaultInfo = {};
  11. }
  12. /**
  13. * 装载属性,只会压入配置过的属性
  14. * @param {*} obj
  15. */
  16. load(obj) {
  17. let info = {};
  18. //合并,后覆盖前,所以必定有默认key
  19. Object.assign(info, this.defaultInfo, obj)
  20. for (let key in this.defaultInfo) {
  21. if (typeof (info[key]) !== 'undefined') {
  22. this.storageInfo[key] = info[key];
  23. }
  24. }
  25. }
  26. /**
  27. * 追加
  28. * @param {*} obj
  29. */
  30. addInfo(obj) {
  31. let info = {};
  32. Object.assign(info, this.defaultInfo, this.storageInfo, obj)
  33. for (let key in this.defaultInfo) {
  34. if (typeof (info[key]) !== 'undefined') {
  35. this.storageInfo[key] = info[key];
  36. }
  37. }
  38. }
  39. //获取类里面的属性
  40. getInfo(key) {
  41. if (key && (key in this.storageInfo)) {
  42. return this.storageInfo[key]
  43. } else {
  44. return this.storageInfo
  45. }
  46. }
  47. //保存到缓存,传进来>默认值
  48. setStorage(obj) {
  49. if (obj) {
  50. this.load(obj);
  51. }
  52. if (!this.storageKey) {
  53. return false;
  54. }
  55. if (Object.getOwnPropertyNames(this.storageInfo).length === 0) {
  56. return false;
  57. }
  58. console.log('11111=>', this.storageKey)
  59. console.log('22222=>', this.storageInfo)
  60. setStorage(this.storageKey, this.storageInfo);
  61. }
  62. //追加到缓存,传进来>缓存>默认值
  63. addStorage(obj) {
  64. if (!this.storageKey) {
  65. return false;
  66. }
  67. let info = {};
  68. let curStorageInfo = getStorage(this.storageKey);
  69. Object.assign(info, curStorageInfo, obj)
  70. this.load(obj);
  71. setStorage(this.storageKey, this.storageInfo);
  72. }
  73. //获取缓存的属性
  74. getStorage(key) {
  75. if (!this.storageKey) {
  76. return false;
  77. }
  78. let info = getStorage(this.storageKey);
  79. Object.assign(this.storageInfo, info)
  80. if (key && (key in this.storageInfo)) {
  81. return this.storageInfo[key]
  82. } else {
  83. return this.storageInfo
  84. }
  85. }
  86. //销毁缓存的属性
  87. destroyStorage() {
  88. if (!this.storageKey) {
  89. return false;
  90. }
  91. removeStorage(this.storageKey)
  92. this.load();
  93. }
  94. }
  95. export default base;