wujingjing
2024-08-29 19b778d2d04bed31ce2e1f167c6ff2fda9906421
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
import type { ComputedRef } from 'vue';
import { computed } from 'vue';
 
/**
 * 
 * 执行函数结果带缓存
 * 需要耗时的函数计算,并且需要传参
 * 为避免每次传参都需要重新计算,可以用该函数缓存结果
 * @example const computedPriceFn = useComputedFn(totalPrice);
 * 原来使用 totalPrice,现在可以使用 computedPriceFn,减少计算次数
 * @returns
 */
export const useComputedFn = <T>(fn: (...args: unknown[]) => T): ((...args: unknown[]) => ComputedRef<T>) => {
    const cache: Map<string, ComputedRef<T>> = new Map();
    // FIXME: 返回值是字符串的时候,有时字符串中会带有双引号
    return (...args: unknown[]) => {
        const cacheKey = JSON.stringify(args);
        if (cache.has(cacheKey)) {
            const cacheValue =  cache.get(cacheKey);
            return cacheValue ;
        }
        const result = computed(() => fn(...args));
        cache.set(cacheKey, result);
        return result;
    };
};