base.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. setStorage(this.storageKey, this.storageInfo);
  59. }
  60. //追加到缓存,传进来>缓存>默认值
  61. addStorage(obj) {
  62. if (!this.storageKey) {
  63. return false;
  64. }
  65. let info = {};
  66. let curStorageInfo = getStorage(this.storageKey);
  67. Object.assign(info, curStorageInfo, obj)
  68. this.load(obj);
  69. setStorage(this.storageKey, this.storageInfo);
  70. }
  71. //获取缓存的属性
  72. getStorage(key) {
  73. if (!this.storageKey) {
  74. return false;
  75. }
  76. let info = getStorage(this.storageKey);
  77. Object.assign(this.storageInfo, info)
  78. if (key && (key in this.storageInfo)) {
  79. return this.storageInfo[key]
  80. } else {
  81. return this.storageInfo
  82. }
  83. }
  84. //销毁缓存的属性
  85. destroyStorage() {
  86. if (!this.storageKey) {
  87. return false;
  88. }
  89. removeStorage(this.storageKey)
  90. this.load();
  91. }
  92. }
  93. export default base;