You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.0 KiB

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