ant-design-vue/components/vc-tree-select/hooks/useKeyValueMap.ts

27 lines
969 B
TypeScript
Raw Normal View History

2021-08-20 13:39:59 +00:00
import type { ComputedRef, Ref } from 'vue';
import { ref } from 'vue';
import { watchEffect } from 'vue';
import type { FlattenDataNode, Key, RawValueType } from '../interface';
/**
* Return cached Key Value map with DataNode.
* Only re-calculate when `flattenOptions` changed.
*/
export default function useKeyValueMap(flattenOptions: ComputedRef<FlattenDataNode[]>) {
const cacheKeyMap: Ref<Map<Key, FlattenDataNode>> = ref(new Map());
const cacheValueMap: Ref<Map<RawValueType, FlattenDataNode>> = ref(new Map());
watchEffect(() => {
const newCacheKeyMap = new Map();
const newCacheValueMap = new Map();
// Cache options by key
flattenOptions.value.forEach((dataNode: FlattenDataNode) => {
newCacheKeyMap.set(dataNode.key, dataNode);
newCacheValueMap.set(dataNode.data.value, dataNode);
});
cacheKeyMap.value = newCacheKeyMap;
cacheValueMap.value = newCacheValueMap;
});
return [cacheKeyMap, cacheValueMap];
}