Files
heroui-vue/apps/docs/components/form.md
T
maoyingjie 53e76f676d fix(demos): restore form, overlay and toast demos to the pinned cn baseline
HD-02 scope, all against heroui ce90ea3 cn sources:

- card: add the text-primary class to the coin icons (source parity);
  card-with-form drops the added required validation and inline business
  note, restores the plain href="#" forgot-password link and the baseline
  alert("表单提交成功!") submit feedback (autocomplete kept: no visible
  impact, allowed by the task card)
- input-group-with-textarea: restore the four Tooltips and the Enter Kbd
  hint; drop the stale "Tooltip 组件尚未迁移" note from input-group.md
- alert-dialog: restore the h-px top light line in custom-styles and the
  truncated/missing description text in sizes/custom-portal/
  custom-animations (+ controlled); align the fluid-slide icon with the
  modal mapping (IconArrowBarUp for gravity-ui:arrow-up-from-line)
- toast: restore the upstream demo layout shells (variants/simple/
  custom-indicator/custom-queue) and the action button default variant:
  ToastActionButton now falls back to the Button defaults (primary/md)
  like upstream ToastActionButton, so variants' actions render primary,
  danger stays danger and default stays tertiary; toast.md defaults fixed
- submit demos: restore baseline feedback and structure — alert() for
  card/fieldset/form/checkbox/checkbox-group/switch/select/combo-box/
  autocomplete and console.log for search/number/time field form examples;
  modal-with-form returns to the close-only footer (no submit/result row);
  drop the added inline status/result rows and the max-w-full/
  max-sm:min-w-0 width guards from the restored demos
- radio-group-validation: add the missing text-muted to the result line;
  label.md invalid example gives the real control its invalid state and
  matches the baseline input shape

Tests re-pinned to the baseline contracts (alert/console/close behavior,
four tooltips + Kbd, positional modal footer); full suite 110 files /
1617 tests, typecheck, build:docs and the m35-m36 tarball contract pass.
2026-10-28 14:10:10 +08:00

186 lines
10 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: Form 表单
description: 用于表单校验与提交处理的包裹组件
component: form
stylesSource: false
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import { Form } from "@heroui-vue/components";
</script>
```
<ComponentPreview name="form-basic" />
## 组件结构
```vue
<script setup lang="ts">
import { Form, Button } from "@heroui-vue/components";
</script>
<template>
<Form>
<!-- 表单字段 -->
<Button type="submit">提交</Button>
<Button type="reset">重置</Button>
</Form>
</template>
```
## 示例
### 渲染函数
上游 `render={(props) => <form {...props} data-custom="foo" />}` 在 Vue 中直接通过 `data-custom="foo"` 透传到同一个原生 `<form>`;无需为添加属性替换根元素。Form 始终保留表单语义,不提供 React `render` prop 或替换为非表单元素的 API。
<ComponentPreview name="form-render-function" />
## 自定义样式
### Tailwind CSS
<ComponentPreview name="form-custom-styles" />
### 全局 CSS
要自定义表单布局与间距,可在 `<Form>` 上使用 `class`,或通过 `@layer components` 添加项目级类。
`Form` 渲染原生 `<form>` 元素,聚焦校验与提交。本库样式包中无专用 BEM 类;从全局 CSS 应用容器样式,控件级自定义请使用字段组件。
```css
@layer components {
.form-layout {
@apply flex flex-col gap-4 rounded-xl border border-border bg-surface p-4 shadow-sm;
}
}
```
```vue
<Form class="form-layout" @submit.prevent="handleSubmit">
<!-- TextField、Input、Button 等 -->
</Form>
```
分组字段与共享布局请使用 [Fieldset](./fieldset),并定位 `.hv-fieldset`、`.hv-fieldset__legend` 等相关类。单个控件请参阅 [TextField](./text-field)、[Input](./input)、[Label](./label)、[FieldError](./field-error) 的全局 CSS 部分。
## 样式参考
本库对提供样式的组件遵循 BEM 方法论。
`Form` 渲染原生 `<form>` 元素,无专用 BEM 类或 variants。通过 `class` 应用布局、间距与表面样式。字段外观与校验状态来自 `TextField`、`Input`、`Label`、`Description`、`FieldError` 等子组件。结构化多字段布局请与 Fieldset 组合使用。
## API 参考
### Form / FormRoot
Form 复用本库共享字段上下文与浏览器 Constraint Validation API。`FormRoot` 是同一组件别名;原生属性、ARIA、class、style 与 DOM 监听器透传到实际 form。
| Prop / 事件 | 类型 | 默认值 | 描述 |
| --------------------------- | ------------------------------------ | --------------------- | ----------------------------------------------------------------------------- |
| `action` | `string` | - | 提交表单数据的 URL;保留浏览器传统提交 |
| `class` | Vue class 绑定 | - | 应用于 form 元素的布局与样式 |
| 默认插槽 | `() => VNodeChild` | - | 表单内容(字段、按钮等) |
| `enctype` | `string` | - | 原生编码类型,如 `multipart/form-data` |
| `method` | `string` | - | 原生提交方法,如 `get` / `post` |
| `@invalid` | `(event: Event) => void` | - | 每个无效控件每次检查通知一次;`preventDefault()` 取消默认焦点,不放行无效提交 |
| `@reset` | `(event: Event) => void` | - | 原生重置事件;可 `preventDefault()` 取消 |
| `@submit` | `(event: SubmitEvent) => void` | - | 校验通过或显式跳过校验时调用;使用 `.prevent` 接管提交 |
| `target` | `string` | - | 提交后显示响应的位置 |
| `validationBehavior` | `'native' \| 'aria'` | `'native'` | 默认字段校验策略;字段可覆盖 |
| `validationErrors` | `Record<string, string \| string[]>` | `{}` | 按字段名映射的服务端错误;编辑该字段后忽略当前响应中的错误 |
| `aria-label` | `string` | - | 表单的无障碍名称 |
| `aria-labelledby` | `string` | - | 标注表单的元素 ID |
| `novalidate` / `noValidate` | `boolean` | `false`(调用方意图) | 为 `true` 或空属性时跳过本库提交检查;实际 DOM 始终有 novalidate,见下文 |
| `render`(上游) | Vue attrs / 默认插槽替代 | - | 添加原生属性直接透传;不移植 React DOMRenderFunction |
公开类型包含 `FormProps`、`FormRootProps`、`FormSlots`、`FormExpose`。实例能力是 Vue 扩展:
| 实例成员 | 类型 | 说明 |
| ------------------ | ------------------------------ | -------------------------------------------------------------------------------------- |
| `element` | `HTMLFormElement \| undefined` | 挂载后实际 form |
| `checkValidity()` | `() => boolean` | 按 native/aria 策略检查并产生 invalid;不自动聚焦 |
| `reportValidity()` | `() => boolean` | 检查并聚焦首个无效字段,除非调用方取消;错误由 FieldError 展示,不重复调用原生气泡校验 |
| `reset()` | `() => void` | 调用原生 form.reset(),遵守取消与既有受控值协议 |
### Form Validation
Form 支持:
- 内置 HTML5 校验属性(`required`、`minLength`、`pattern` 等)。
- TextField 的同步 `validate(value)` 校验函数。
- FieldError 展示字段错误。
- 校验通过后处理提交。
- `validationErrors` 提供服务端校验结果。
#### Validation Behavior
`validationBehavior` 控制校验展示方式:
- **`native`**(默认):有错误时阻止提交,提交尝试后显示错误并聚焦首个无效字段。
- **`aria`**:实时显示错误语义,允许提交,由调用方处理。
可在表单级或单个字段级设置。Form 在实际 DOM 上使用 `novalidate` 接管验证,再按每个控件的 `data-validation-behavior` 或表单默认值检查,因此允许混合两种策略。调用方显式 `novalidate`、提交按钮的 `formnovalidate` 可跳过提交检查。即使监听 `@submit.capture`,无效提交也先由 Form 拦截。
`validationErrors` 使用新的响应对象更新。编辑一个字段只忽略当前响应里该字段的错误,不修改传入对象。同步 `validate` 不接受 Promise;异步请求和竞态由调用方管理。原生外部 `form` 关联的控件也在验证集合中;字段的服务端错误上下文仍按 Vue 组件祖先继承,DOM form 关联不会跨组件树注入上下文。
### Form Submission
表单支持传统 `action` 提交、JavaScript 事件处理及 FormData API:
```vue
<script setup lang="ts">
function handleSubmit(event: SubmitEvent) {
const formData = new FormData(event.currentTarget as HTMLFormElement);
const data = Object.fromEntries(formData);
console.log("Form data:", data);
}
</script>
<template>
<Form @submit.prevent="handleSubmit">
<!-- 表单字段 -->
</Form>
</template>
```
默认插槽不维护第二份表单值。禁用控件不进入 FormData,只读控件保留。reset 恢复非受控初始值,受控值仍由父级决定;取消 reset 会保留当前值。`element.submit()` 遵循浏览器行为并绕过校验与 submit 事件,常规提交应使用按钮或 `element.requestSubmit()`。
### Integration with Form Fields
Form 与共享字段组件协作:
- **TextField**:带标签与校验的文本输入。
- **Checkbox / CheckboxGroup**:布尔选择及多选集合。
- **RadioGroup**:多选一。
- **Switch**:开关控件。
- **Button**:提交与重置。
值、错误关联与重置使用各字段现有协议;复杂日期、颜色、数值和集合字段的具体差异仍以各自组件页为准。
### Advanced Usage
可组合第三方校验库,将结果映射到 `validationErrors`;无需为使用 Input 强制引入其他库。自定义错误焦点使用 `@invalid` 并调用 `event.preventDefault()`。共享上下文和集成验证示例见[字段与表单基础](/fields)。不提供 React Form Context、React 函数 action 或完整 React Aria ValidationResult。
## 无障碍
- 原生 `<form>` 语义。
- 使用 `aria-label` 或 `aria-labelledby` 提供 form landmark 名称。
- 无效提交默认聚焦首个无效字段;组合字段聚焦其可操作部件。
- 错误通过 FieldError 与真实控件的 ARIA 描述关联。
- `validationBehavior="aria"` 保留错误语义但不阻止提交。
三个预览沿用固定源的字段、文案、校验、布局与提交反馈:有效提交以 `alert` 展示表单数据,`reset` 重置字段与校验错误。React 专属机制按上述 Vue 方式适配。当前仅支持浏览器客户端;未将完整读屏矩阵或逐像素比较视为已完成。
## 相关案例
[字段与表单基础](/fields)提供服务端错误注入、原生 FormData 和重置的额外组合示例。
## 相关组件
[TextField](./text-field) · [Fieldset](./fieldset) · [FieldError](./field-error) · [Button](./button)