storage.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /**
  2. * 缓存数据优化
  3. * const storage = require('@/utils/storage');
  4. * import storage from '@/utils/storage'
  5. * 使用方法 【
  6. * 一、设置缓存
  7. * string storage.setKey('k', 'string你好啊');
  8. * json storage.setKey('k', { "b": "3" }, 2);
  9. * array storage.setKey('k', [1, 2, 3]);
  10. * boolean storage.setKey('k', true);
  11. * 二、读取缓存
  12. * 默认值 storage.getKey('k')
  13. * string storage.getKey('k', '你好')
  14. * json storage.getKey('k', { "a": "1" })
  15. * 三、移除/清理
  16. * 移除: storage.remove('k');
  17. * 清理:storage.clear();
  18. * 】
  19. * @type {String}
  20. */
  21. import {inArray} from "@/utils/util";
  22. const postfix = '_expiry' // 缓存有效期后缀
  23. /**
  24. * @param {function}
  25. */
  26. class Storage {
  27. /**
  28. * 设置缓存
  29. * @param {string} k [键名]
  30. * @param {*} v [键值]
  31. * @param {string|number|null} t [时间、单位秒]
  32. */
  33. static setKey(k, v, t = null) {
  34. uni.setStorageSync(k, v)
  35. const seconds = parseInt(t)
  36. if (seconds > 0) {
  37. let timestamp = Date.parse(new Date())
  38. timestamp = timestamp / 1000 + seconds
  39. uni.setStorageSync(k + postfix, timestamp + '')
  40. } else {
  41. uni.removeStorageSync(k + postfix)
  42. }
  43. }
  44. /**
  45. * 获取缓存
  46. * @param {string} k [键名]
  47. * @param {*} def [获取为空时默认]
  48. */
  49. static getKey(k, def = false) {
  50. const deadTime = parseInt(uni.getStorageSync(k + postfix))
  51. if (deadTime) {
  52. if (parseInt(deadTime) < Date.parse(new Date()) / 1000) {
  53. if (def) {
  54. return def
  55. } else {
  56. return false
  57. }
  58. }
  59. }
  60. const res = uni.getStorageSync(k)
  61. if (res) {
  62. return res
  63. }
  64. if (def == undefined || def == "") {
  65. def = false
  66. }
  67. return def
  68. }
  69. /**
  70. * 删除指定缓存
  71. * @param {Object} k
  72. */
  73. static remove(k) {
  74. uni.removeStorageSync(k)
  75. uni.removeStorageSync(k + postfix)
  76. }
  77. /**
  78. * 清理所有缓存
  79. * @return {[type]} [description]
  80. */
  81. static clear() {
  82. uni.clearStorageSync()
  83. }
  84. static clearOtherKey(key = []) {
  85. const res = uni.getStorageInfoSync();
  86. res.keys.forEach((it) => {
  87. if (!inArray(it, key)) {
  88. this.remove(it)
  89. }
  90. })
  91. }
  92. }
  93. export default Storage