cache.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { defineStore } from 'pinia'
  2. interface CacheItem {
  3. value : any
  4. expire : number // 过期时间戳
  5. }
  6. export const useCacheStore = defineStore('cache', {
  7. state: () => ({
  8. cache: {} as Record<string, CacheItem>
  9. }),
  10. actions: {
  11. set(key : string, value : any, ttl ?: number) {
  12. const expire = typeof ttl === 'undefined'
  13. ? Number.MAX_SAFE_INTEGER
  14. : Date.now() + ttl * 1000;
  15. this.cache[key] = { value, expire }
  16. // 同步到本地存储
  17. uni.setStorageSync(key, JSON.stringify({ value, expire }))
  18. },
  19. get<T = any>(key : string) : T | null {
  20. // 优先内存中读取
  21. if (this.cache[key] && this.cache[key].expire > Date.now()) {
  22. return this.cache[key].value
  23. }
  24. // 本地存储读取
  25. const data = uni.getStorageSync(key)
  26. if (data) {
  27. try {
  28. const parsed : CacheItem = JSON.parse(data)
  29. if (parsed.expire > Date.now()) {
  30. this.cache[key] = parsed
  31. return parsed.value
  32. }
  33. this.remove(key)
  34. } catch (e) {
  35. console.error('缓存解析失败', e)
  36. }
  37. }
  38. return null
  39. },
  40. remove(key : string) {
  41. delete this.cache[key]
  42. uni.removeStorageSync(key)
  43. },
  44. clear() {
  45. this.cache = {}
  46. uni.clearStorageSync()
  47. }
  48. }
  49. })