UNPKG

@ithinkdt/core

Version:

iThinkDT Core

80 lines (71 loc) 2.66 kB
/* eslint-disable unicorn/no-thenable */ import { isRef, nextTick, shallowReactive, watch } from 'vue' import { getDict } from './get-dict' function _useDict(dictType, getType, valueTypeOrOptions) { const valueType = typeof valueTypeOrOptions === 'string' ? valueTypeOrOptions : valueTypeOrOptions?.valueType ?? 'string' const { forceCache = false, onGet, hideDisabled = getType === 'list', } = typeof valueTypeOrOptions === 'object' ? valueTypeOrOptions : {} let $returns if (isRef(dictType)) { const isGetMap = getType === 'map' $returns = shallowReactive(isGetMap ? new Map() : []) $returns.__on = [] $returns.loading = false watch( dictType, () => { $returns.loading = true isGetMap ? $returns.clear() : ($returns.length = 0) if (dictType.value) { const $ret = getDict(dictType.value, getType, valueType, forceCache, hideDisabled, (dicts) => { nextTick(() => { if (isGetMap) { for (const [k, v] of $ret.entries) $returns.set(k, v) } else { $returns.push(...$ret) } onGet?.(dicts) $returns.loading = false for (const on of $returns.__on) { try { on?.($ret) } catch (error) { console.error(error) } } }) }) } }, { immediate: true }, ) $returns.then = (on) => { $returns.__on.push(on) } } else { $returns = getDict(dictType, getType, valueType, forceCache, hideDisabled, (dicts) => { nextTick(() => { $returns.loading = false onGet?.(dicts) }) }) $returns.loading ??= true $returns.then = (on) => { $returns.$.then(() => { on?.($returns) }) } } $returns.dicts = $returns return $returns } export function useDict(dictType, valueTypeOrOptions = 'string') { return _useDict(dictType, 'list', valueTypeOrOptions) } export function useDictMap(dictType, valueTypeOrOptions = 'string') { return _useDict(dictType, 'map', valueTypeOrOptions) }