diff --git a/docs/src/components/common-ui/vben-form.md b/docs/src/components/common-ui/vben-form.md index f7986304..0206dbee 100644 --- a/docs/src/components/common-ui/vben-form.md +++ b/docs/src/components/common-ui/vben-form.md @@ -229,7 +229,7 @@ useVbenForm 返回的第二个参数,是一个对象,包含了一些表单 | --- | --- | --- | | submitForm | 提交表单 | `(e:Event)=>Promise>` | | resetForm | 重置表单 | `()=>Promise` | -| setValues | 设置表单值 | `()=>Promise>` | +| setValues | 设置表单值, 默认会过滤不在schema中定义的field, 可通过filterFields形参关闭过滤 | `(fields: Record, filterFields?: boolean, shouldValidate?: boolean) => Promise` | | getValues | 获取表单值 | `(fields:Record,shouldValidate: boolean = false)=>Promise` | | validate | 表单校验 | `()=>Promise` | | resetValidate | 重置表单校验 | `()=>Promise` | diff --git a/packages/@core/ui-kit/form-ui/src/form-api.ts b/packages/@core/ui-kit/form-ui/src/form-api.ts index 459ba080..77f3204e 100644 --- a/packages/@core/ui-kit/form-ui/src/form-api.ts +++ b/packages/@core/ui-kit/form-ui/src/form-api.ts @@ -17,6 +17,8 @@ import { StateHandler, } from '@vben-core/shared/utils'; +import { objectPick } from '@vueuse/core'; + const merge = createMerge((originObj, key, updates) => { if (Array.isArray(originObj[key]) && Array.isArray(updates)) { originObj[key] = updates; @@ -182,12 +184,25 @@ export class FormApi { } } + /** + * 设置表单值 + * @param fields record + * @param filterFields 过滤不在schema中定义的字段 默认为true + * @param shouldValidate + */ async setValues( fields: Record, + filterFields: boolean = true, shouldValidate: boolean = false, ) { const form = await this.getForm(); - form.setValues(fields, shouldValidate); + if (!filterFields) { + form.setValues(fields, shouldValidate); + return; + } + const fieldNames = this.state?.schema?.map((item) => item.fieldName) ?? []; + const filteredFields = objectPick(fields, fieldNames); + form.setValues(filteredFields, shouldValidate); } async submitForm(e?: Event) {