145a208687
HD-04 scope, against heroui ce90ea3 cn sources: - stale/fictional content: input.md no longer claims TextField is unmigrated; color-field.md no longer claims ColorPicker is private; header.md drops the fictional Header.Root subcomponent and the stale 'menus not migrated' wording (MenuSection label registration is now documented from HeaderRoot source); radio-group.md drops three copied CheckboxGroup wordings (variant override is Radio's, scalar emits, native single-value submit); input-otp.md drops the fictional data-complete state and lists the real missing upstream props - toggle-button disabled row now matches the real CSS hooks (:disabled / [aria-disabled], with data-disabled as a marker only) - part API / CSS classes / interactive states restored per pinned sources: button (full class lists + real variable-based global CSS), accordion (per-part tables + variant/state lists), card (per-part tables + variant list), switch (SwitchGroup snippet + Switch/ SwitchGroup class lists + states), color-field Group (class list + states), input-otp (variant notes, global CSS, class/state lists); input-group gains the two upstream usage chapters - RelatedComponents restored from the pinned componentRelationships (first-3, filtered against componentsMap): 64 pages rewritten, list-box/slider sections added, 7 empty-mapping pages' fabricated entries removed; RelatedShowcases left unmigrated with its real data inventory recorded (2 cases, showcase-site cards) - defaults unified on implementation evidence: granularity (inferred day/minute) and visibleYears (full min-max span, no "or 20" fallback); HD-03 hand-offs resolved (trigger focus-visible noted for HD-06, width guards kept) - new demos: header-collection-grouping (MenuSection/ListBoxSection label wiring), empty-state-collection (collection empty slot); empty-state page deduplicated with a boundary compatibility note - ComponentPreview minHeight/isBgSolid restored per the 30 upstream marks; tabs-overflow max-w-full kept after measuring internal scroll - tests: +3 header registration/demo cases, +1 empty-state collection case; full suite 110 files / 1630 tests, typecheck and build:docs pass
186 lines
10 KiB
Markdown
186 lines
10 KiB
Markdown
---
|
||
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 和重置的额外组合示例。
|
||
|
||
## 相关组件
|
||
|
||
[Button 按钮](./button) · [Fieldset 字段组](./fieldset) · [TextField 文本输入框](./text-field)
|