---
name: "form"
mode: "component"
versionRequirements:
  - { name: "基础库", version: "2.10.0" }
title: "form - 表单"
---

## form

> [VERSION] 基础库 >= 2.10.0

### 描述

表单容器，用于提交表单内组件的值。


#### 事件

| 事件名 | 类型 | 描述 |
| --- | --- | --- |
| `submit` | `(event: FormSubmitEvent) => void` | 携带 form 中的数据触发 |
| `reset` | `(event: FormResetEvent) => void` | 表单重置时触发 |

**FormSubmitEvent**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `type` | `"submit"` |  |
| `detail` | `FormSubmitDetail` |  |

**FormResetEvent**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `type` | `"reset"` |  |
| `detail` | `FormResetDetail` |  |

### 示例代码

#### 基础用法

*index.tyml*

```xml
<form bind:submit="onSubmit">
  <input name="username" placeholder="请输入用户名" />
  <button form-type="submit">提交</button>
</form>
```

*index.tyss*

```css
input {
  margin: 20rpx;
  padding: 10rpx;
  border: 1rpx solid #ccc;
}
```

*index.js*

```javascript
Page({
  onSubmit(e) {
    console.log('表单数据:', e.detail.value);
  },
});
```

#### 完整表单（提交与重置）

*index.tyml*

```xml
<form bind:submit="onSubmit" bind:reset="onReset">
  <view class="form-item">
    <text>开关：</text>
    <switch name="switch" />
  </view>
  <view class="form-item">
    <text>输入框：</text>
    <input name="input" placeholder="请输入" />
  </view>
  <view class="form-item">
    <text>选择：</text>
    <checkbox-group name="fruits">
      <label><checkbox value="apple" />苹果</label>
      <label><checkbox value="banana" />香蕉</label>
    </checkbox-group>
  </view>
  <button form-type="submit" type="primary">提交</button>
  <button form-type="reset">重置</button>
</form>
```

*index.tyss*

```css
.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}
button {
  margin-top: 10rpx;
}
```

*index.js*

```javascript
Page({
  onSubmit(e) {
    console.log('提交:', e.detail.value);
  },
  onReset() {
    console.log('表单已重置');
  },
});
```


### 常见问题

#### 小程序 form 表单可以静默触发吗

不支持，需要用户点击触发。
