Form 全局配置
ElhForm 支持通过 setFormConfig 设置全局默认行为,例如:
- 全局
el-form默认props - 全局
el-col默认props - 各类型组件默认
props - 默认占位文案(
placeholder) - 扩展组件注册表(
type: 'extend'使用) - 异步数据解析器(
asyncDataParser)
基础用法
TIP
建议在 main.ts / main.js 中初始化一次。
ts
import { setFormConfig } from 'elplus-enhance'
import IconSelect from './components/IconSelect.vue'
setFormConfig({
formProps: {
labelSuffix: ':'
},
colProps: {
span: 12
},
componentProps: {
input: { clearable: true },
number: { controlsPosition: 'right' },
select: { clearable: true, filterable: true },
IconSelect: { size: 'default' } // 对应 type: 'extend' + component: 'IconSelect'
},
componentPlaceholder: {
input: (option) => `请输入${option.label || '该项'}`,
number: (option) => `请输入${option.label || '该项'}`,
select: (option) => `请选择${option.label || '该项'}`
},
components: {
IconSelect
}
})异步数据解析器
当配置项使用 asyncData 时,内部会调用全局 asyncDataParser 解析返回值。 默认解析逻辑等价于:
ts
asyncDataParser: async (func, formInstance, ...args) => {
return new Promise((resolve, reject) => {
func(formInstance, ...args)
.then((res) => resolve(res?.data || res))
.catch(reject)
})
}也就是说默认优先取 res.data,否则取 res 本身。
WARNING
自定义 asyncDataParser 时,请确保返回 Promise(或 async 函数)。
配置项(FormConfig)
| 名称 | 说明 | 类型 | 默认值 |
|---|---|---|---|
formProps | 全局 el-form 默认 props | Partial<FormProps> | {} |
colProps | 全局 el-col 默认 props | ColProps | {} |
componentProps | 各组件默认 props,按类型名或扩展组件名取值 | Record<string, any> | {} |
componentPlaceholder | 组件默认占位文案,支持字符串或函数 | Record<string, string | ((option: FormComponentOption) => string)> | 内置 input/number/select/radio/cascader/date |
components | 扩展组件注册表,供 type: 'extend' 使用 | Record<string, any> | {} |
asyncDataParser | 异步数据解析函数 | (func: Function, form: FormInstance, ...args: any[]) => any | 内置解析器 |
相关 API
setFormConfig(config: FormConfig): void:合并写入全局配置getFormConfig(key: keyof FormConfig): any:读取某项全局配置