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;
|
};
|
};
|