useSearch.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { ref, unref, nextTick } from 'vue'
  2. import { FormSchema, FormSetProps } from '@/components/Form'
  3. import { SearchExpose, SearchProps } from '@/components/Search'
  4. export const useSearch = () => {
  5. // Search实例
  6. const searchRef = ref<SearchExpose>()
  7. /**
  8. * @param ref Search实例
  9. * @param elRef ElForm实例
  10. */
  11. const register = (ref: SearchExpose) => {
  12. searchRef.value = ref
  13. }
  14. const getSearch = async () => {
  15. await nextTick()
  16. const search = unref(searchRef)
  17. if (!search) {
  18. console.error('The Search is not registered. Please use the register method to register')
  19. }
  20. return search
  21. }
  22. // 一些内置的方法
  23. const methods = {
  24. /**
  25. * @description 设置search组件的props
  26. * @param field FormItem的field
  27. */
  28. setProps: async (props: SearchProps = {}) => {
  29. const search = await getSearch()
  30. search?.setProps(props)
  31. if (props.model) {
  32. search?.setValues(props.model)
  33. }
  34. },
  35. /**
  36. * @description 设置form的值
  37. * @param data 需要设置的数据
  38. */
  39. setValues: async (data: Recordable) => {
  40. const search = await getSearch()
  41. search?.setValues(data)
  42. },
  43. /**
  44. * @description 设置schema
  45. * @param schemaProps 需要设置的schemaProps
  46. */
  47. setSchema: async (schemaProps: FormSetProps[]) => {
  48. const search = await getSearch()
  49. search?.setSchema(schemaProps)
  50. },
  51. /**
  52. * @description 新增schema
  53. * @param formSchema 需要新增数据
  54. * @param index 在哪里新增
  55. */
  56. addSchema: async (formSchema: FormSchema, index?: number) => {
  57. const search = await getSearch()
  58. search?.addSchema(formSchema, index)
  59. },
  60. /**
  61. * @description 删除schema
  62. * @param field 删除哪个数据
  63. */
  64. delSchema: async (field: string) => {
  65. const search = await getSearch()
  66. search?.delSchema(field)
  67. },
  68. /**
  69. * @description 获取表单数据
  70. * @returns form data
  71. */
  72. getFormData: async <T = Recordable>(): Promise<T> => {
  73. const search = await getSearch()
  74. return search?.formModel as T
  75. }
  76. }
  77. return {
  78. searchRegister: register,
  79. searchMethods: methods
  80. }
  81. }