storage.js 2.0 KB

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