storage.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import config from "../model/config"
  2. import dayjs from "dayjs";
  3. const EXSPACE = "ex_space";
  4. const isUp = false;// 升级本地存储 新增过期失效功能 默认不打开 设置为true后生效
  5. export default {
  6. getStorage(space = config.NAMESPACE) {
  7. const res = wx.getStorageSync(space);
  8. return JSON.parse(res || "{}");
  9. },
  10. setItem(key, val, ex) {
  11. const storage = this.getStorage();
  12. storage[key] = val;
  13. if (isUp && ex){
  14. let exObj = this.getStorage(EXSPACE);
  15. exObj[key] = dayjs().valueOf() +ex;
  16. wx.setStorageSync(EXSPACE, JSON.stringify(exObj))
  17. }
  18. wx.setStorageSync(config.NAMESPACE, JSON.stringify(storage))
  19. },
  20. getItem(key) {
  21. const storage = this.getStorage();
  22. const exObj = this.getStorage(EXSPACE);
  23. if (isUp){
  24. if (exObj && exObj[key] ) {
  25. if (exObj[key] > dayjs().valueOf()){
  26. }else {
  27. this.clearItem(key)
  28. return null;
  29. }
  30. }
  31. }
  32. return storage[key];
  33. },
  34. clearItem(key) {
  35. const storage = this.getStorage();
  36. delete storage[key]
  37. wx.setStorageSync(config.NAMESPACE, JSON.stringify(storage))
  38. },
  39. clearAll() {
  40. wx.removeStorageSync(config.NAMESPACE)
  41. }
  42. }