useFormInstanceMethods.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { IAnyObject } from '../typings/base-type';
  2. import { Ref, SetupContext, getCurrentInstance, toRaw, type EmitsOptions } from 'vue';
  3. import { cloneDeep, forOwn, isFunction } from 'lodash-es';
  4. import { AForm, IVFormComponent } from '../typings/v-form-component';
  5. import { Form } from 'ant-design-vue';
  6. export function useFormInstanceMethods<E extends EmitsOptions = EmitsOptions>(
  7. props: IAnyObject,
  8. formdata,
  9. context: SetupContext<E>,
  10. _formInstance: Ref<AForm | null>,
  11. ) {
  12. /**
  13. * 绑定props和on中的上下文为parent
  14. */
  15. const bindContext = () => {
  16. const instance = getCurrentInstance();
  17. const vm = instance?.parent;
  18. if (!vm) return;
  19. (props.formConfig.schemas as IVFormComponent[]).forEach((item) => {
  20. // 绑定 props 中的上下文
  21. forOwn(item.componentProps, (value: any, key) => {
  22. if (isFunction(value)) {
  23. item.componentProps![key] = value.bind(vm);
  24. }
  25. });
  26. // 绑定事件监听(v-on)的上下文
  27. forOwn(item.on, (value: any, key) => {
  28. if (isFunction(value)) {
  29. item.componentProps![key] = value.bind(vm);
  30. }
  31. });
  32. });
  33. };
  34. bindContext();
  35. const { emit } = context;
  36. const useForm = Form.useForm;
  37. const { resetFields, validate, clearValidate, validateField } = useForm(formdata, []);
  38. const submit = async () => {
  39. //const _result = await validate();
  40. const data = cloneDeep(toRaw(formdata.value));
  41. emit?.('submit', data);
  42. props.formConfig.submit?.(data);
  43. return data;
  44. };
  45. return {
  46. validate,
  47. validateField,
  48. resetFields,
  49. clearValidate,
  50. submit,
  51. };
  52. }