import type { FormProps, FormActionType, UseFormReturnType, FormSchema } from '../types/form'; import type { NamePath } from 'ant-design-vue/lib/form/interface'; import type { DynamicProps } from '/#/utils'; import { ref, onUnmounted, unref, nextTick, watch } from 'vue'; import { error } from '/@/utils/log'; import { getDynamicProps } from '/@/utils'; export declare type ValidateFields = (nameList?: NamePath[]) => Promise; type Props = Partial>; export function useForm(props?: Props): UseFormReturnType { const formRef = ref>(null); const loadedRef = ref>(false); async function getForm() { const form = unref(formRef); if (!form) { error('未获得表单实例,请确保在执行表单操作时表单已存在!'); } await nextTick(); return form as FormActionType; } function register(instance: FormActionType) { onUnmounted(() => { formRef.value = null; loadedRef.value = null; }); if (unref(loadedRef) && instance === unref(formRef)) return; formRef.value = instance; loadedRef.value = true; watch( () => props, () => { props && instance.setProps(getDynamicProps(props)); }, { immediate: true, deep: true, }, ); } const methods: FormActionType = { scrollToField: async (name: NamePath, options?: ScrollOptions | undefined) => { const form = await getForm(); form.scrollToField(name, options); }, setProps: async (formProps: Partial) => { const form = await getForm(); form.setProps(formProps); }, updateSchema: async (data: Partial | Partial[]) => { const form = await getForm(); form.updateSchema(data); }, resetSchema: async (data: Partial | Partial[]) => { const form = await getForm(); form.resetSchema(data); }, clearValidate: async (name?: string | string[]) => { const form = await getForm(); form.clearValidate(name); }, resetFields: async () => { getForm().then(async (form) => { await form.resetFields(); }); }, removeSchemaByFiled: async (field: string | string[]) => { unref(formRef)?.removeSchemaByFiled(field); }, // TODO promisify getFieldsValue: () => { return unref(formRef)?.getFieldsValue() as T; }, setFieldsValue: async (values: T) => { const form = await getForm(); form.setFieldsValue(values); }, appendSchemaByField: async ( schema: FormSchema | FormSchema[], prefixField: string | undefined, first: boolean, ) => { const form = await getForm(); form.appendSchemaByField(schema, prefixField, first); }, submit: async (): Promise => { const form = await getForm(); return form.submit(); }, validate: async (nameList?: NamePath[]): Promise => { const form = await getForm(); return form.validate(nameList); }, validateFields: async (nameList?: NamePath[]): Promise => { const form = await getForm(); return form.validateFields(nameList); }, }; return [register, methods]; }