useForm.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import type { Form, FormExpose } from '@/components/Form'
  2. import type { ElForm } from 'element-plus'
  3. import type { FormProps } from '@/components/Form/src/types'
  4. import { FormSchema, FormSetPropsType } from '@/types/form'
  5. export const useForm = (props?: FormProps) => {
  6. // From实例
  7. const formRef = ref<typeof Form & FormExpose>()
  8. // ElForm实例
  9. const elFormRef = ref<ComponentRef<typeof ElForm>>()
  10. /**
  11. * @param ref Form实例
  12. * @param elRef ElForm实例
  13. */
  14. const register = (ref: typeof Form & FormExpose, elRef: ComponentRef<typeof ElForm>) => {
  15. formRef.value = ref
  16. elFormRef.value = elRef
  17. }
  18. const getForm = async () => {
  19. await nextTick()
  20. const form = unref(formRef)
  21. if (!form) {
  22. console.error('The form is not registered. Please use the register method to register')
  23. }
  24. return form
  25. }
  26. // 一些内置的方法
  27. const methods: {
  28. setProps: (props: Recordable) => void
  29. setValues: (data: Recordable) => void
  30. getFormData: <T = Recordable | undefined>() => Promise<T>
  31. setSchema: (schemaProps: FormSetPropsType[]) => void
  32. addSchema: (formSchema: FormSchema, index?: number) => void
  33. delSchema: (field: string) => void
  34. } = {
  35. setProps: async (props: FormProps = {}) => {
  36. const form = await getForm()
  37. form?.setProps(props)
  38. if (props.model) {
  39. form?.setValues(props.model)
  40. }
  41. },
  42. setValues: async (data: Recordable) => {
  43. const form = await getForm()
  44. form?.setValues(data)
  45. },
  46. /**
  47. * @param schemaProps 需要设置的schemaProps
  48. */
  49. setSchema: async (schemaProps: FormSetPropsType[]) => {
  50. const form = await getForm()
  51. form?.setSchema(schemaProps)
  52. },
  53. /**
  54. * @param formSchema 需要新增数据
  55. * @param index 在哪里新增
  56. */
  57. addSchema: async (formSchema: FormSchema, index?: number) => {
  58. const form = await getForm()
  59. form?.addSchema(formSchema, index)
  60. },
  61. /**
  62. * @param field 删除哪个数据
  63. */
  64. delSchema: async (field: string) => {
  65. const form = await getForm()
  66. form?.delSchema(field)
  67. },
  68. /**
  69. * @returns form data
  70. */
  71. getFormData: async <T = Recordable>(): Promise<T> => {
  72. const form = await getForm()
  73. return form?.formModel as T
  74. }
  75. }
  76. props && methods.setProps(props)
  77. return {
  78. register,
  79. elFormRef,
  80. methods
  81. }
  82. }