# BasicForm 表单组件
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/01.%20%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/03.%20%E7%BB%84%E4%BB%B6%E5%BA%93%E6%96%87%E6%A1%A3/03.%20%E8%A1%A8%E5%8D%95%E7%BB%84%E4%BB%B6/BasicForm


# BasicForm 表单组件

## 组件说明

基于 Ant Design Vue Form 封装的配置化表单组件，支持动态渲染、折叠展开、表单验证、自动提交等功能。

## 组件路径

```
src/components/Form/
├── index.ts
├── src/
│   ├── BasicForm.vue          # 主组件
│   ├── components/
│   │   ├── FormItem.vue       # 表单项组件
│   │   ├── FormAction.vue     # 表单操作按钮组件
│   │   ├── ApiSelect.vue      # API下拉选择
│   │   ├── ApiTreeSelect.vue  # API树形选择
│   │   └── ApiRadioGroup.vue  # API单选组
│   ├── hooks/
│   │   ├── useForm.ts         # 表单 Hook
│   │   ├── useFormEvents.ts   # 表单事件处理
│   │   ├── useFormValues.ts   # 表单值处理
│   │   ├── useFormContext.ts  # 表单上下文
│   │   ├── useAdvanced.ts     # 展开/收起功能
│   │   └── useAutoFocus.ts    # 自动聚焦
│   └── types/
│       ├── form.ts            # 表单类型定义
│       └── formItem.ts        # 表单项类型定义
```

## 导入方式

```typescript
import { BasicForm, useForm, FormSchema } from '@/components/Form';
```

## BasicForm 组件

### Props

| 参数 | 说明 | 类型 | 默认值 | 必填 |
|------|------|------|--------|------|
| layout | 表单布局 | `'vertical' \| 'inline' \| 'horizontal'` | 'horizontal' | 否 |
| model | 表单数据对象 | `Recordable` | {} | 否 |
| labelWidth | 所有表单项的标签宽度 | `number \| string` | - | 否 |
| labelAlign | 标签对齐方式 | `'left' \| 'right'` | 'right' | 否 |
| labelCol | 表单项标签布局配置 | `Partial<ColEx> \| null` | - | 否 |
| wrapperCol | 表单项控件布局配置 | `Partial<ColEx> \| null` | - | 否 |
| rowProps | 整个表单的 Row 配置 | `RowProps` | - | 否 |
| baseRowStyle | 通用行样式 | `CSSProperties` | {} | 否 |
| baseColProps | 通用列配置 | `Partial<ColEx>` | - | 否 |
| schemas | 表单项配置数组 | `FormSchema[]` | [] | 是 |
| mergeDynamicData | 合并到动态控件的函数值 | `Recordable` | - | 否 |
| compact | 紧凑模式（用于搜索表单） | `boolean` | false | 否 |
| emptySpan | 空白列跨度 | `number \| Partial<ColEx>` | - | 否 |
| size | 表单内部组件尺寸 | `'default' \| 'small' \| 'large'` | 'default' | 否 |
| disabled | 是否禁用整个表单 | `boolean` | false | 否 |
| fieldMapToTime | 时间间隔字段映射（将一个字段拆分为多个） | `FieldMapToTime` | [] | 否 |
| fieldMapToNumber | 数字间隔字段映射 | `FieldMapToNumber` | [] | 否 |
| autoSetPlaceHolder | 自动设置占位符 | `boolean` | - | 否 |
| autoSubmitOnEnter | 输入框按回车自动提交 | `boolean` | false | 否 |
| rulesMessageJoinLabel | 校验信息是否添加 label | `boolean` | - | 否 |
| showAdvancedButton | 是否显示展开/收起按钮 | `boolean` | false | 否 |
| autoFocusFirstItem | 是否聚焦第一个输入框 | `boolean` | false | 否 |
| autoAdvancedCol | 超过指定列数默认折叠 | `number` | 3 | 否 |
| alwaysShowLines | 折叠时始终保持显示的行数 | `number` | - | 否 |
| showActionButtonGroup | 是否显示操作按钮组 | `boolean` | true | 否 |
| resetButtonOptions | 重置按钮配置 | `Partial<ButtonProps>` | - | 否 |
| submitButtonOptions | 提交按钮配置 | `Partial<ButtonProps>` | - | 否 |
| actionColOptions | 操作列配置 | `Partial<ColEx>` | - | 否 |
| showResetButton | 是否显示重置按钮 | `boolean` | true | 否 |
| showSubmitButton | 是否显示提交按钮 | `boolean` | true | 否 |
| submitOnReset | 重置时是否提交表单 | `boolean` | - | 否 |
| resetFunc | 自定义重置函数 | `() => Promise<void>` | - | 否 |
| submitFunc | 自定义提交函数 | `() => Promise<void>` | - | 否 |
| transformDateFunc | 日期转换函数 | `(date: unknown) => string` | - | 否 |
| colon | 是否显示冒号 | `boolean` | - | 否 |
| autoSearch | 值变化时自动搜索提交 | `boolean` | false | 否 |
| name | 表单名称（用于表单识别） | `string` | - | 否 |

### Emits

| 事件名 | 说明 | 回调参数 |
|--------|------|----------|
| advanced-change | 展开/收起状态变化 | `() => void` |
| reset | 表单重置时触发 | `() => void` |
| submit | 表单提交时触发 | `() => void` |
| register | 注册表单实例时触发 | `(formActionType: Partial<FormActionType>) => void` |

### Expose Methods

| 方法名 | 说明 | 参数 | 返回值 |
|--------|------|------|--------|
| getFieldsValue | 获取表单值 | - | `Recordable` |
| setFieldsValue | 设置表单值 | `<T>(values: T) => Promise<void>` | `Promise<void>` |
| resetFields | 重置表单 | `() => Promise<void>` | `Promise<void>` |
| updateSchema | 更新表单配置 | `(data: Partial<FormSchema> \| Partial<FormSchema>[]) => Promise<void>` | `Promise<void>` |
| resetSchema | 重置表单配置 | `(data: Partial<FormSchema> \| Partial<FormSchema>[]) => Promise<void>` | `Promise<void>` |
| setProps | 设置表单属性 | `(formProps: Partial<FormProps>) => Promise<void>` | `Promise<void>` |
| getProps | 获取表单属性 | - | `ComputedRef<Partial<FormProps>>` |
| getSchemaByField | 根据字段名获取表单配置 | `(field: string) => Nullable<FormSchema>` | `FormSchema \| null` |
| removeSchemaByFiled | 删除指定字段的表单项 | `(field: string \| string[]) => Promise<void>` | `Promise<void>` |
| appendSchemaByField | 在指定字段后添加表单项 | `(schema: FormSchema, prefixField?: string, first?: boolean) => Promise<void>` | `Promise<void>` |
| clearValidate | 清除校验 | `(name?: string \| string[]) => Promise<void>` | `Promise<void>` |
| validateFields | 校验指定字段 | `(nameList?: NamePath[], options?: ValidateOptions) => Promise<Recordable>` | `Promise<Recordable>` |
| validate | 校验表单 | `(nameList?: NamePath[]) => Promise<Recordable>` | `Promise<Recordable>` |
| submit | 提交表单 | `() => Promise<void>` | `Promise<void>` |
| scrollToField | 滚动到指定字段 | `(name: NamePath, options?: ScrollOptions) => Promise<void>` | `Promise<void>` |

### Slots

| 插槽名 | 说明 | 作用域参数 |
|--------|------|------------|
| formHeader | 表单头部内容 | - |
| formFooter | 表单底部内容 | - |
| resetBefore | 重置按钮之前的内容 | - |
| submitBefore | 提交按钮之前的内容 | - |
| advanceBefore | 展开按钮之前的内容 | - |
| advanceAfter | 展开按钮之后的内容 | - |
| [动态插槽] | 根据 FormSchema.slot 匹配的自定义插槽 | `{ model, field, schema, ... }` |

## FormSchema 类型

完整 `FormSchema` 类型定义：

```typescript
interface FormSchema {
  // ===== 基础属性 =====
  field: string;                    // 字段名（必填）
  label: string | VNode | Fn;       // 标签文本
  changeEvent?: string;             // 值变化触发的事件，默认 'change'
  valueField?: string;              // v-model 绑定的变量名，默认 'value'

  // ===== 辅助文本 =====
  subLabel?: string;                // 辅助文本
  helpMessage?: string | string[] | ((params: RenderCallbackParams) => string | string[]);
  helpComponentProps?: Partial<HelpComponentProps>;

  // ===== 组件配置 =====
  component: ComponentType;         // 组件类型
  componentProps?: ((opt: {
    schema: FormSchema;
    tableAction: TableActionType;
    formActionType: FormActionType;
    formModel: Recordable;
  }) => Recordable) | object;

  // ===== 校验规则 =====
  required?: boolean | ((params: RenderCallbackParams) => boolean);
  rules?: Rule[];                   // 校验规则
  rulesMessageJoinLabel?: boolean;  // 校验信息是否添加 label

  // ===== 布局配置 =====
  labelWidth?: string | number;     // 标签宽度（优先级高于全局）
  disabledLabelWidth?: boolean;     // 禁用 labelWidth 全局设置
  itemProps?: Partial<FormItem>;    // FormItem 配置
  colProps?: Partial<ColEx>;        // 列配置
  span?: number;                    // 跨度（详情模式下）

  // ===== 默认值 =====
  defaultValue?: unknown;           // 默认值

  // ===== 显示控制 =====
  isAdvanced?: boolean;             // 是否为高级字段
  ifShow?: boolean | ((params: RenderCallbackParams) => boolean);  // 是否显示（保留 DOM）
  show?: boolean | ((params: RenderCallbackParams) => boolean);   // 是否显示（移除 DOM）
  dynamicDisabled?: boolean | ((params: RenderCallbackParams) => boolean);  // 动态禁用

  // ===== 自定义渲染 =====
  render?: (params: RenderCallbackParams) => VNode | VNode[] | string;  // 自定义表单项内容
  renderColContent?: (params: RenderCallbackParams) => VNode | VNode[] | string;  // 自定义列内容
  renderComponentContent?: ((params: RenderCallbackParams) => VNode | VNode[] | string) | VNode | VNode[] | string;

  // ===== 插槽 =====
  slot?: string;                    // 自定义插槽名（在 form-item 内）
  colSlot?: string;                 // 自定义列插槽名

  // ===== 动态属性 =====
  dynamicRules?: (params: RenderCallbackParams) => Rule[];  // 动态校验规则
  dynamicPropskey?: string;         // 动态 props 的 key
  dynamicPropsVal?: (params: RenderCallbackParams) => unknown;  // 动态 props 的值

  // ===== 其他 =====
  suffix?: string | number | ((params: RenderCallbackParams) => string | number);  // 后缀
  buss?: unknown;                   // 自定义业务属性
  labelLength?: number;             // label 字数控制
  auth?: string;                    // 权限控制（v-auth 指令）
}
```

### RenderCallbackParams 类型

```typescript
interface RenderCallbackParams {
  schema: FormSchema;
  values: Recordable;
  model: Recordable;
  field: string;
}
```

### Rule 类型

```typescript
type Rule = RuleObject & {
  trigger?: 'blur' | 'change' | ['change', 'blur'];
};
```

## useForm Hook

### 基本用法

```typescript
const [register, methods] = useForm(props?: Props);
```

### 参数类型

```typescript
type Props = Partial<DynamicProps<FormProps>>;
```

### 返回值类型

```typescript
type UseFormReturnType = [RegisterFn, FormActionType];

type RegisterFn = (formInstance: FormActionType) => void;
```

### FormActionType 方法

与 BasicForm 组件的 Expose Methods 一致。

## 常用组件类型

### 组件类型列表

| 组件类型 | ComponentType | 说明 |
|----------|---------------|------|
| 输入框 | `Input` | 基础输入框 |
| 密码输入框 | `InputPassword` | 密码输入 |
| 数字输入框 | `InputNumber` | 数字输入 |
| 文本域 | `InputTextArea` | 多行文本输入 |
| 下拉选择 | `Select` | 基础下拉选择 |
| API下拉选择 | `ApiSelect` | 动态加载下拉选项 |
| 树形选择 | `TreeSelect` | 树形结构选择 |
| API树形选择 | `ApiTreeSelect` | 动态加载树形选项 |
| 单选组 | `RadioGroup` | 单选按钮组 |
| 单选按钮组 | `RadioButtonGroup` | 按钮式单选组 |
| API单选组 | `ApiRadioGroup` | 动态加载单选项 |
| 复选框 | `Checkbox` | 单个复选框 |
| 复选组 | `CheckboxGroup` | 复选框组 |
| 开关 | `Switch` | 开关切换 |
| 滑动条 | `Slider` | 滑动选择 |
| 评分 | `Rate` | 星级评分 |
| 日期选择 | `DatePicker` | 日期选择器 |
| 日期范围选择 | `RangePicker` | 日期区间选择 |
| 月份选择 | `MonthPicker` | 月份选择器 |
| 时间选择 | `TimePicker` | 时间选择器 |
| 上传 | `Upload` | 文件上传 |
| 图片上传 | `JImageUpload` | 图片上传 |
| 富文本编辑器 | `JEditor` | 富文本编辑 |
| 代码编辑器 | `JCodeEditor` | 代码编辑 |
| 字典标签选择 | `JDictSelectTag` | 字典选择 |
| 分类选择 | `JCategorySelect` | 分类选择 |
| 用户选择 | `JSelectUser` | 用户选择 |
| 部门选择 | `JSelectDept` | 部门选择 |
| Cron表达式 | `JEasyCron` | Cron 表达式编辑 |

### 联机表单专用组件

| 组件类型 | ComponentType | 说明 |
|----------|---------------|------|
| 级联选择 | `OnlineSelectCascade` | 联机表单级联选择 |
| 关联卡片 | `LinkTableCard` | 关联表卡片 |
| 关联选择 | `LinkTableSelect` | 关联表选择 |

## 基础用法

```vue
<template>
  <BasicForm
    :labelWidth="100"
    :schemas="formSchemas"
    :actionColOptions="{ span: 24 }"
    @register="registerForm"
    @submit="handleSubmit"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { BasicForm, FormSchema, useForm } from '@/components/Form';
import { useMessage } from '@/hooks/web/useMessage';

const { createMessage } = useMessage();

const formSchemas: FormSchema[] = [
  {
    field: 'username',
    label: '用户名',
    component: 'Input',
    rules: [{ required: true, message: '请输入用户名' }],
    componentProps: {
      placeholder: '请输入用户名',
    },
  },
  {
    field: 'password',
    label: '密码',
    component: 'InputPassword',
    rules: [{ required: true, message: '请输入密码' }],
    componentProps: {
      placeholder: '请输入密码',
    },
  },
  {
    field: 'email',
    label: '邮箱',
    component: 'Input',
    rules: [
      { required: true, message: '请输入邮箱' },
      { type: 'email', message: '邮箱格式不正确' },
    ],
  },
  {
    field: 'role',
    label: '角色',
    component: 'Select',
    componentProps: {
      options: [
        { label: '管理员', value: 'admin' },
        { label: '普通用户', value: 'user' },
      ],
    },
  },
  {
    field: 'status',
    label: '状态',
    component: 'CheckboxGroup',
    componentProps: {
      options: [
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' },
      ],
    },
  },
];

const [registerForm, { getFieldsValue, setFieldsValue, validate }] = useForm();

const handleSubmit = async (values: any) => {
  console.log('表单值:', values);
  createMessage.success('提交成功');
};
</script>
```

## 高级用法

### 条件显示

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { BasicForm, FormSchema } from '@/components/Form';

const formSchemas: FormSchema[] = [
  {
    field: 'type',
    label: '类型',
    component: 'Select',
    componentProps: {
      options: [
        { label: '个人', value: 'personal' },
        { label: '企业', value: 'company' },
      ],
    },
  },
  {
    field: 'companyName',
    label: '企业名称',
    component: 'Input',
    // 仅当类型为企业时显示
    ifShow: ({ model }) => model.type === 'company',
  },
  {
    field: 'idCard',
    label: '身份证号',
    component: 'Input',
    // 仅当类型为个人时显示
    ifShow: ({ model }) => model.type === 'personal',
  },
];
</script>
```

### 动态禁用

```typescript
const formSchemas: FormSchema[] = [
  {
    field: 'email',
    label: '邮箱',
    component: 'Input',
    rules: [{ required: true, message: '请输入邮箱' }],
    // 当用户名未填写时禁用
    dynamicDisabled: ({ model }) => !model.username,
  },
];
```

### 动态校验规则

```typescript
const formSchemas: FormSchema[] = [
  {
    field: 'password',
    label: '密码',
    component: 'InputPassword',
    // 根据模式动态设置校验规则
    dynamicRules: ({ model }) => {
      const rules = [{ required: true, message: '请输入密码' }];
      if (model.mode === 'strict') {
        rules.push({
          min: 12,
          message: '密码长度不能少于12位',
        });
      }
      return rules;
    },
  },
];
```

### 自定义插槽

```vue
<template>
  <BasicForm
    :schemas="formSchemas"
    @register="registerForm"
  >
    <template #customField="{ model, field }">
      <div class="custom-field">
        <span>当前值: {{ model[field] }}</span>
        <a-button @click="handleCustomAction">自定义操作</a-button>
      </div>
    </template>
  </BasicForm>
</template>

<script setup lang="ts">
import { BasicForm, FormSchema, useForm } from '@/components/Form';

const formSchemas: FormSchema[] = [
  {
    field: 'name',
    label: '名称',
    component: 'Input',
  },
  {
    field: 'customField',
    label: '自定义字段',
    slot: 'customField',
  },
];

const [registerForm] = useForm();

const handleCustomAction = () => {
  console.log('自定义操作');
};
</script>
```

### 表单项布局

```typescript
const formSchemas: FormSchema[] = [
  {
    field: 'field1',
    label: '字段1',
    component: 'Input',
    colProps: {
      span: 12,  // 占12列
      offset: 0, // 偏移量
      order: 1,  // 顺序
    },
  },
  {
    field: 'field2',
    label: '字段2',
    component: 'Input',
    colProps: { span: 12 },
  },
  {
    field: 'field3',
    label: '字段3（独占一行）',
    component: 'Input',
    colProps: { span: 24 },
  },
];
```

### 时间字段映射

```typescript
const formSchemas: FormSchema[] = [
  {
    field: 'dateRange',
    label: '日期范围',
    component: 'RangePicker',
    componentProps: {
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
    },
  },
];

// fieldMapToTime 会将 dateRange 的数组值映射到两个独立字段
const fieldMapToTime = [
  ['dateRange', ['startTime', 'endTime'], 'YYYY-MM-DD HH:mm:ss']
];
```

### 动态更新表单配置

```typescript
const [registerForm, { updateSchema, appendSchemaByField, removeSchemaByFiled }] = useForm({
  schemas: formSchemas,
});

// 更新现有字段配置
updateSchema({
  field: 'username',
  componentProps: {
    disabled: true,
  },
});

// 在指定字段后添加新字段
appendSchemaByField(
  {
    field: 'newField',
    label: '新字段',
    component: 'Input',
  },
  'username'  // 插入到 username 后面
);

// 删除指定字段
removeSchemaByFiled('password');
```

### 紧凑模式

适用于搜索表单，减少间距：

```vue
<template>
  <BasicForm
    :schemas="searchSchemas"
    :compact="true"
    :showAdvancedButton="true"
    :actionColOptions="{ span: 24 }"
    @register="registerForm"
    @submit="handleSearch"
  />
</template>
```

## 注意事项

1. **字段唯一性**: `field` 必须唯一，重复会导致数据覆盖
2. **日期组件**: 使用日期组件时务必配置 `valueFormat`，否则可能导致格式化错误
3. **校验触发**: 默认按 `change` 触发校验，可通过 `rules[].trigger` 修改
4. **动态属性**: `dynamicDisabled`、`dynamicRules` 等属性支持函数形式，响应表单值变化
5. **权限控制**: 使用 `auth` 属性可通过 v-auth 指令控制字段显隐
6. **性能优化**: 大型表单建议使用 `showAdvancedButton` 折叠功能

---

*组件文档版本: 2.0.0*
*最后更新: 2026-04-22*
