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