1. 程式人生 > 實用技巧 >微信小程式封裝快取過期時間

微信小程式封裝快取過期時間

utils新建storage.js檔案

  1. var dtime = '_deadtime';
  2. function put(k, v, t) {
  3. wx.setStorageSync(k, v)
  4. var seconds = parseInt(t);
  5. if (seconds > 0) {
  6. var timestamp = Date.parse(new Date());
  7. timestamp = timestamp / 1000 + seconds;
  8. wx.setStorageSync(k + dtime, timestamp + "")
  9. } else {
  10. wx.removeStorageSync(k + dtime)
  11. }
  12. }
  13. function get(k, def) {
  14. var deadtime = parseInt(wx.getStorageSync(k + dtime))
  15. if (deadtime) {
  16. if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
  17. if (def) { return def; } else { return; }
  18. }
  19. }
  20. var res = wx.getStorageSync(k);
  21. if (res) {
  22. return res;
  23. } else {
  24. return def;
  25. }
  26. }
  27. function remove(k) {
  28. wx.removeStorageSync(k);
  29. wx.removeStorageSync(k + dtime);
  30. }
  31. function clear() {
  32. wx.clearStorageSync();
  33. }
  34. module.exports = {
  35. put: put,
  36. get: get,
  37. remove: remove,
  38. clear: clear,
  39. }

js引用

let util = require('../../utils/storage.js');

使用方法:

  1. 設定快取:util.put('key','value',604800) 表示設定快取失效時間為一週;
  2. 獲取快取:util.get('key')
  3. 清除快取:util.remove('key')
  4. 清除所有快取:util.clear() https://blog.csdn.net/weixin_44694538/article/details/103728983