Просмотр исходного кода

perf: setValues method of the form supports assigning values only to keys that exist in the schema (#4508)

* fix: hover border style same as antd style when validate error

* fix: hover border style same as antd style when validate error

* feat(@vben-core/form-ui): Default form validation rules applicable to selector components

* fix: Missing the default required label style for components such as select

* fix: the focus style and antd of the input box validation failure should be consistent

* fix: the focus style and antd of the input box validation failure should be consistent

* fix: some antd components failed to verify styles

* perf: setValues method of the form supports assigning values only to keys that exist in the schema

* docs: update form component docs

---------

Co-authored-by: vince <vince292007@gmail.com>
LinaBell 1 год назад
Родитель
Сommit
bb6057cac3

+ 1 - 1
docs/src/components/common-ui/vben-form.md

@@ -229,7 +229,7 @@ useVbenForm 返回的第二个参数,是一个对象,包含了一些表单
 | --- | --- | --- |
 | submitForm | 提交表单 | `(e:Event)=>Promise<Record<string,any>>` |
 | resetForm | 重置表单 | `()=>Promise<void>` |
-| setValues | 设置表单值 | `()=>Promise<Record<string,any>>` |
+| setValues | 设置表单值, 默认会过滤不在schema中定义的field, 可通过filterFields形参关闭过滤 | `(fields: Record<string, any>, filterFields?: boolean, shouldValidate?: boolean) => Promise<void>` |
 | getValues | 获取表单值 | `(fields:Record<string, any>,shouldValidate: boolean = false)=>Promise<void>` |
 | validate | 表单校验 | `()=>Promise<void>` |
 | resetValidate | 重置表单校验 | `()=>Promise<void>` |

+ 16 - 1
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<string, any>,
+    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) {