useForm.ts 2.4 KB

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