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