-
Notifications
You must be signed in to change notification settings - Fork 138
/
useCacheData.ts
70 lines (54 loc) 路 1.76 KB
/
useCacheData.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* @license
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://github.com/IDuxFE/idux/blob/main/LICENSE
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { SearchState } from './useSearchStates'
import { onUnmounted } from 'vue'
export interface CacheDataContext {
setCacheData: (itemKey: string, segmentName: string, dataKey: string, data: any) => void
getCacheData: (itemKey: string, segmentName: string, dataKey: string) => void
clearCacheData: (searchStates?: SearchState[]) => void
}
export function useCacheData(): CacheDataContext {
const cacheDataMap = new Map<string, Map<string, Record<string, any>>>()
const setCacheData = (itemKey: string, segmentName: string, dataKey: string, data: any) => {
let dataMap = cacheDataMap.get(itemKey)
if (!dataMap) {
dataMap = new Map<string, Record<string, any>>()
cacheDataMap.set(itemKey, dataMap)
}
let segmentData = dataMap.get(segmentName)
if (!segmentData) {
segmentData = {
[dataKey]: data,
}
dataMap.set(segmentName, segmentData)
} else {
segmentData[dataKey] = data
}
}
const getCacheData = (itemKey: string, segmentName: string, dataKey: string) => {
return cacheDataMap.get(itemKey)?.get(segmentName)?.[dataKey]
}
const clearCacheData = (searchStates?: SearchState[]) => {
if (!searchStates) {
cacheDataMap.clear()
return
}
const stateKeys = new Set(searchStates.map(state => state.key))
for (const key of cacheDataMap.keys()) {
if (!stateKeys.has(key)) {
cacheDataMap.delete(key)
}
}
}
onUnmounted(clearCacheData)
return {
setCacheData,
getCacheData,
clearCacheData,
}
}