diff --git a/packages/vant/src/form/Form.tsx b/packages/vant/src/form/Form.tsx index 3483f2a4a..a2d90c6f0 100644 --- a/packages/vant/src/form/Form.tsx +++ b/packages/vant/src/form/Form.tsx @@ -151,10 +151,10 @@ export default defineComponent({ }; const getValues = () => - children.reduce((form, field) => { + children.reduce>((form, field) => { form[field.name] = field.formValue.value; return form; - }, {} as Record); + }, {}); const submit = () => { const values = getValues(); @@ -179,6 +179,7 @@ export default defineComponent({ useExpose({ submit, validate, + getValues, scrollToField, resetValidation, }); diff --git a/packages/vant/src/form/README.md b/packages/vant/src/form/README.md index d67514dbf..9c2642ef6 100644 --- a/packages/vant/src/form/README.md +++ b/packages/vant/src/form/README.md @@ -541,6 +541,7 @@ Use [ref](https://v3.vuejs.org/guide/component-template-refs.html) to get Form i | --- | --- | --- | --- | | submit | Submit form | - | - | | validate | Validate form | _name?: string \| string[]_ | _Promise_ | +| getValues `v3.4.8` | Get current form values | - | _Record_ | | resetValidation | Reset validation | _name?: string \| string[]_ | - | | scrollToField | Scroll to field | _name: string, alignToTop: boolean_ | - | diff --git a/packages/vant/src/form/README.zh-CN.md b/packages/vant/src/form/README.zh-CN.md index 41904eb48..d0aa56c56 100644 --- a/packages/vant/src/form/README.zh-CN.md +++ b/packages/vant/src/form/README.zh-CN.md @@ -579,6 +579,7 @@ export default { | --- | --- | --- | --- | | submit | 提交表单,与点击提交按钮的效果等价 | - | - | | validate | 验证表单,支持传入 `name` 来验证单个或部分表单项 | _name?: string \| string[]_ | _Promise_ | +| getValues `v3.4.8` | 获取所有表单项当前的值 | - | _Record_ | | resetValidation | 重置表单项的验证提示,支持传入 `name` 来重置单个或部分表单项 | _name?: string \| string[]_ | - | | scrollToField | 滚动到对应表单项的位置,默认滚动到顶部,第二个参数传 false 可滚动至底部 | _name: string, alignToTop: boolean_ | - | diff --git a/packages/vant/src/form/test/methods.spec.tsx b/packages/vant/src/form/test/methods.spec.tsx index 5a3b4d9ec..8d3322cf0 100644 --- a/packages/vant/src/form/test/methods.spec.tsx +++ b/packages/vant/src/form/test/methods.spec.tsx @@ -137,3 +137,19 @@ test('scrollToField method', () => { formRef.value?.scrollToField('A'); expect(fn).toHaveBeenCalledTimes(1); }); + +test('getValues method should return all current values', () => { + const formRef = ref(); + mount({ + render() { + return ( +
+ + + + ); + }, + }); + + expect(formRef.value?.getValues()).toEqual({ A: '123', B: '456' }); +}); diff --git a/packages/vant/src/form/types.ts b/packages/vant/src/form/types.ts index aa1dc53db..f5e372f27 100644 --- a/packages/vant/src/form/types.ts +++ b/packages/vant/src/form/types.ts @@ -4,6 +4,7 @@ import type { FormProps } from './Form'; export type FormExpose = { submit: () => void; validate: (name?: string | string[] | undefined) => Promise; + getValues: () => Record; scrollToField: ( name: string, options?: boolean | ScrollIntoViewOptions | undefined