storage.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import {isAllNull} from "js-fast-way"
  2. import website from '@/config/index'
  3. //获取缓存
  4. export const getStorage = (key, debug = false) => {
  5. let obj = uni.getStorageSync(website.key + '-' + key), content;
  6. if (isAllNull(obj)) {
  7. return '';
  8. }
  9. try {
  10. obj = JSON.parse(obj);
  11. } catch {
  12. return obj;
  13. }
  14. if (debug) {
  15. return obj;
  16. }
  17. if (obj.dataType === 'string') {
  18. content = obj.content;
  19. } else if (obj.dataType === 'number') {
  20. content = Number(obj.content);
  21. } else if (obj.dataType === 'boolean') {
  22. content = Boolean(obj.content);
  23. } else if (obj.dataType === 'object') {
  24. content = obj.content;
  25. }
  26. return content ?? '';
  27. }
  28. //保存缓存
  29. export const setStorage = (key, value) => {
  30. try {
  31. uni.setStorageSync(website.key + '-' + key, JSON.stringify({
  32. dataType: typeof (value),
  33. content: value ?? '',
  34. datetime: new Date().getTime()
  35. }));
  36. } catch (e) {
  37. uni.showToast({
  38. title: '本地数据缓存失败',
  39. icon: 'none'
  40. });
  41. }
  42. }
  43. //删除缓存
  44. export const delStorage = (key) => {
  45. try {
  46. uni.removeStorageSync(website.key + '-' + key);
  47. } catch {
  48. }
  49. }
  50. //清理缓存
  51. export const clearStorage = () => {
  52. try {
  53. uni.clearStorageSync();
  54. } catch {}
  55. }