storage.js 2.0 KB

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