useForm.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. 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. },
  39. setValues: async (data: Recordable) => {
  40. const form = await getForm()
  41. form?.setValues(data)
  42. },
  43. /**
  44. * @param schemaProps 需要设置的schemaProps
  45. */
  46. setSchema: async (schemaProps: FormSetPropsType[]) => {
  47. const form = await getForm()
  48. form?.setSchema(schemaProps)
  49. },
  50. /**
  51. * @param formSchema 需要新增数据
  52. * @param index 在哪里新增
  53. */
  54. addSchema: async (formSchema: FormSchema, index?: number) => {
  55. const form = await getForm()
  56. form?.addSchema(formSchema, index)
  57. },
  58. /**
  59. * @param field 删除哪个数据
  60. */
  61. delSchema: async (field: string) => {
  62. const form = await getForm()
  63. form?.delSchema(field)
  64. },
  65. /**
  66. * @returns form data
  67. */
  68. getFormData: async <T = Recordable>(): Promise<T> => {
  69. const form = await getForm()
  70. return form?.formModel as T
  71. }
  72. }
  73. props && methods.setProps(props)
  74. return {
  75. register,
  76. elFormRef,
  77. methods
  78. }
  79. }