UNPKG

@tplc/business

Version:

79 lines (75 loc) 2.1 kB
import { inject, onMounted, onUnmounted, ref, Ref, watch } from 'vue' import { FilterItemProps, Option } from '../types' import { FORM_KEY } from '../../../constants' const useSelect = ( props: FilterItemProps, { model, extraModel, onOpen, }: { model: Ref<string | string[] | undefined> extraModel?: Ref<Record<string, any>> onOpen?: () => void }, ) => { const options = ref<Option[]>(props.options || []) const form = inject<Ref<Record<string, any>>>(FORM_KEY) const onItemClick = (item: Option, valueName?: string) => { let val: string[] | string | undefined const currentValue = valueName ? extraModel?.value[valueName] : model.value if (props.mode === 'multiple') { if (typeof currentValue === 'object' && currentValue.includes(item.value as string)) { val = currentValue.filter((v) => v !== item.value) } else { val = [...(currentValue || []), item.value as string] } } else if (currentValue === item.value) { val = undefined } else { val = item.value } if (valueName && extraModel) { extraModel.value[valueName] = val } else { model.value = val } } const getOptions = async () => { if (props.apiPath) { const { data } = await uni.$lcb.http.post<Option[]>(props.apiPath, { ...props.apiParams, ...form?.value, }) options.value = data } } onMounted(async () => { getOptions() if (onOpen) uni.$on('drop-open', onOpen) }) onUnmounted(() => { if (onOpen) uni.$off('drop-open', onOpen) }) const getChecked = (item: Option, valueName?: string) => { const currentValue = valueName ? extraModel?.value[valueName] : model.value if (Array.isArray(currentValue)) { return currentValue.includes(`${item.value}`) } else { return Boolean(currentValue && currentValue === item.value) } } watch( () => form?.value?.addressName, () => { getOptions() }, ) return { options, getOptions, getChecked, onItemClick, } } export default useSelect