编辑 | blame | 历史 | 原始文档

前端表单规范

本文档定义 Valor 前端表单弹窗的尺寸、布局与对齐规范。模块开发架构见 前端模块开发.md。


1. 全局默认值

表单全局配置在 src/adapter/form.ts 中定义,**不允许在单个表单中覆盖**:

配置项 值 说明
labelWidth 108px 所有表单 label 统一宽度
labelAlign 右对齐(框架默认) 不显式设置
控件宽度 w-full 通过 commonConfig.componentProps.class 全局注入
必填校验 $t('ui.formRules.required', [label]) 输入类用 rules: 'required',下拉类用 rules: 'selectRequired'
// adapter/form.ts 全局配置
setupVbenForm({
  config: {
    commonConfig: {
      componentProps: { class: 'w-full' },
    },
    labelWidth: 108,
  },
});

2. 弹窗尺寸

弹窗宽度根据表单复杂度和附加内容选择,统一通过 class 设置:

const [Modal, modalApi] = useVbenModal({
  class: 'w-[{宽度}px]',
  // ...
});

2.1 宽度对照表

复杂度 宽度 适用场景 示例
简单 600px 1-3 字段表单、确认操作 认领弹窗、扫描输入
中等 720-800px 4-6 字段表单、选择器弹窗 物品选择、配件查询
标准 900px 6-10 字段表单 订单表单、产品表单、分派表单
大型 960px 表单 + 内嵌 Grid 出货单(表单 + 物品表格 + 扫码)
超大型 980-1100px 复合 UI(卡片选择器 + 表单 + Grid) 入库单、采购单、审批详情

2.2 选用规则

字段数量 + 无附加内容        → 900px
字段数量 + 附件管理器        → 900px
字段数量 + 内嵌子表格        → 960px
表单 + 卡片/购物车式选择器    → 980-1000px
完整详情展示(只读)         → 960-1100px
简单操作(≤3 字段)          → 600-720px

MODAL_WIDTH 常量(#/constants/modal)提供 SMALL=600 / MEDIUM=700 / LARGE=900 / XLARGE=960 四档,推荐简单弹窗使用常量,复杂弹窗直接写像素值。


3. 表单布局

3.1 单列布局(默认)

绝大多数表单使用单列布局,不设置 wrapperClass:

const [Form, formApi] = useVbenForm({
  schema: useEditFormSchema(),
  showDefaultActions: false,
});
┌──────────────────────────────────────┐
│  Label 1    [ Input                ] │
│  Label 2    [ Select               ] │
│  Label 3    [ InputNumber          ] │
│  Label 4    [ DatePicker           ] │
│  Remark     [ Textarea             ] │
│             [                      ] │
│             [                      ] │
└──────────────────────────────────────┘

3.2 双列布局

字段数 ≥ 8 且字段较短时,使用 grid-cols-2 双列布局:

const [Form, formApi] = useVbenForm({
  schema: useXxxFormSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});
┌────────────────────────┬────────────────────────┐
│  Label 1  [ Input    ] │  Label 2  [ Select   ] │
│  Label 3  [ Input    ] │  Label 4  [ Input    ] │
│  Label 5  [ Textarea                    ]       │
│          [                                ]       │
└──────────────────────────────────────────────────┘

需要跨列的字段使用 formItemClass: 'col-span-2':

// 宽字段占满整行
{
  component: 'Input',
  fieldName: 'orderTitle',
  label: $t('order.orderTitle'),
  formItemClass: 'col-span-2',
},

// 备注永远跨列
{
  component: 'Textarea',
  fieldName: 'remark',
  label: $t('system.remark'),
  formItemClass: 'col-span-2',
  componentProps: { rows: 3 },
},

// 内嵌子表格占满整行(含边框容器)
{
  component: 'Slot',
  fieldName: 'skuSlot',
  slot: 'skuSlot',
  formItemClass: 'col-span-full',
  label: $t('inventory.sku.list'),
},

3.3 何时用双列

条件 布局
字段 ≤ 6 单列
字段 7-10,无长文本字段 双列
字段 ≥ 8,含 Divider 分组 单列(Divider 不适合双列)
任意字段数 + 内嵌 Grid 双列(Grid 区域 col-span-full)

当前项目仅使用 grid-cols-2,不使用 grid-cols-3 或 grid-cols-4。


4. 字段排列顺序

表单字段按以下顺序排列,从上到下:

顺序 字段类型 说明
1 编码/标识 如 orderNo,通常 disabled: true(自动生成)
2 类型/分类 如 orderType、productId,通常 rules: 'required'
3 关联选择 如 customerId(ApiSelect)、orderId
4 名称/标题 如 orderTitle,可跨列
5 状态/优先级 如 priority、status,通常有 defaultValue
6 数值/日期 如 expectedItemQty、expectedDeliveryTime
7 备注 Textarea,rows: 3,始终在最后

示例(订单表单):

export function useOrderFormSchema(): VbenFormSchema[] {
  return [
    { component: 'Select',      fieldName: 'orderType',           rules: 'required' },
    { component: 'Input',       fieldName: 'orderNo',             componentProps: { disabled: true } },
    { component: 'ApiSelect',   fieldName: 'customerId' },
    { component: 'Select',      fieldName: 'sourceChannel',       defaultValue: 1 },
    { component: 'Input',       fieldName: 'orderTitle',          formItemClass: 'col-span-2' },
    { component: 'Input',       fieldName: 'customerOrderNo' },
    { component: 'Select',      fieldName: 'priority',            defaultValue: 2 },
    { component: 'InputNumber', fieldName: 'expectedItemQty',     rules: 'required' },
    { component: 'DatePicker',  fieldName: 'expectedDeliveryTime' },
    { component: 'Textarea',    fieldName: 'remark',              formItemClass: 'col-span-2', componentProps: { rows: 3 } },
  ];
}

5. 字段分组

5.1 Divider 分组

当表单字段可以按逻辑分组(如公司信息 + 联系人信息)时,使用 Divider 组件:

{
  component: 'Divider',
  fieldName: 'divider0',
  label: $t('basic.customer.companyInfo'),  // 分组标题
},
// ...公司信息字段...

{
  component: 'Divider',
  fieldName: 'divider1',
  label: $t('basic.customer.contact1.title'),
},
// ...联系人字段...

Divider 的 fieldName 命名为 divider + 序号,如 divider0、divider1。

5.2 视觉分组(模板层)

复杂弹窗在模板中使用带边框的容器对区域做视觉分隔:

<!-- 标准分隔容器 -->
<div class="rounded-lg border border-gray-200 p-4">
  <Form />
</div>

<!-- 带底色的信息提示区 -->
<div class="mt-4 rounded-lg border border-blue-200 bg-blue-50 p-2 text-sm">
  提示信息...
</div>

<!-- 多个区域垂直排列 -->
<div class="space-y-4">
  <div class="rounded-lg border border-gray-200 p-4">区域1</div>
  <div class="rounded-lg border border-gray-200 p-4">区域2</div>
</div>

6. 弹窗表单生命周期

所有表单弹窗遵循统一的生命周期:

onOpenChange(isOpen)
  ├── if (!isOpen) return                    // 关闭时不处理
  ├── formApi.resetForm()                    // 1. 重置表单
  ├── formApi.setValues({ status: 1 })       // 2. 设置默认值
  ├── const data = modalApi.getData()        // 3. 读取传入数据
  ├── if (!data?.id) → 新建模式               // 4. 判断模式
  └── if (data?.id) → 编辑模式
       ├── const detail = await getXxx(id)   // 5. 拉取详情
       ├── currentId.value = detail.id       // 6. 记录 ID
       └── formApi.setValues({...})          // 7. 回填表单

onConfirm()
  ├── formApi.validate()                     // 1. 校验
  ├── if (!valid) return                     // 2. 校验失败则中止
  ├── formApi.getValues()                    // 3. 获取表单值
  ├── modalApi.lock()                        // 4. 锁定弹窗(防重复提交)
  ├── try { API 调用 } → emits + close      // 5. 成功:通知 + 关闭
  └── catch { modalApi.unlock() }            // 6. 失败:解锁

7. 复杂表单模式

7.1 表单 + 附件管理器

附件管理器放在 <Form /> 下方:

<template>
  <Modal :title="modalTitle">
    <Form />
    <AttachmentManager
      ref="attachmentManagerRef"
      :business-id="currentId"
      :max-count="10"
      :max-size="50"
    />
  </Modal>
</template>

提交时从附件管理器获取 ID 列表:

const attachmentIds = attachmentManagerRef.value?.getAttachmentIds() || [];
const submitData = { ...values, attachmentIds };

7.2 表单 + 内嵌子表格

表单和子表格放在同一个边框容器中,通过 Slot 组件预留嵌入位置:

// data.ts 中定义 Slot
{
  component: 'Slot',
  fieldName: 'skuSlot',
  slot: 'skuSlot',
  formItemClass: 'col-span-full',
  label: $t('inventory.sku.list'),
},
<!-- 模板中填充 Slot -->
<Modal :title="modalTitle">
  <Form>
    <template #skuSlot>
      <div class="mb-2 flex justify-end">
        <Button type="primary" size="small" @click="addSkuRow">
          {{ $t('common.add') }}
        </Button>
      </div>
      <SkuGrid />
    </template>
  </Form>
</Modal>

7.3 表单 + 扫码输入 + Grid

表单、扫码框和物品表格放在同一个边框容器中:

<Modal :title="modalTitle">
  <div class="space-y-4">
    <div class="rounded-lg border border-gray-200 p-4">
      <Form />
      <div class="mt-2 flex items-center justify-between">
        <div class="text-sm font-medium">{{ $t('shipment.itemList') }}</div>
        <Input
          :value="scanCode"
          class="w-64"
          :placeholder="$t('shipment.itemScanPlaceholder')"
          @press-enter="handleScanAdd"
        />
      </div>
      <ItemsGrid />
    </div>
  </div>
</Modal>

7.4 自定义 Footer(多操作按钮)

当弹窗需要多个操作(如「暂存」+「提交审核」)时,覆盖 Footer:

<Modal :title="modalTitle">
  <template #footer>
    <Space>
      <Button @click="handleDraft">{{ $t('common.saveDraft') }}</Button>
      <Button type="primary" :loading="loading" @click="handleSubmit">
        {{ $t('common.submit') }}
      </Button>
    </Space>
  </template>

  <!-- 表单内容 -->
</Modal>

7.5 只读详情弹窗

无表单、仅展示详情时,设置 :footer="false" 隐藏按钮,使用 Descriptions 组件:

<Modal :title="modalTitle" :footer="false">
  <div class="space-y-4">
    <Descriptions bordered size="small" :column="2" :items="[...]" />
    <div>
      <div class="mb-2 text-sm font-medium">{{ $t('task.itemList') }}</div>
      <ItemGrid />
    </div>
  </div>
</Modal>

8. 常用字段模板

必填输入

{ component: 'Input', fieldName: 'code', label: $t('xxx.code'), rules: 'required' }

必填下拉

{ component: 'Select', fieldName: 'type', label: $t('xxx.type'), rules: 'selectRequired',
  componentProps: { options: TYPE_OPTIONS } }

自动生成编码(禁用)

{ component: 'Input', fieldName: 'orderNo', label: $t('order.orderNo'),
  componentProps: { disabled: true, placeholder: $t('order.orderNoAuto') } }

带搜索的异步下拉

{ component: 'ApiSelect', fieldName: 'customerId', label: $t('order.customer'),
  componentProps: {
    api: fetchCustomerOptions,
    allowClear: true, immediate: true,
    showSearch: true, filterOption: false,
    labelField: 'companyName', valueField: 'id',
  } }

树形下拉

{ component: 'ApiTreeSelect', fieldName: 'categoryId', label: $t('xxx.category'),
  componentProps: {
    allowClear: true, showSearch: true,
    treeNodeFilterProp: 'categoryName',
    fieldNames: { label: 'categoryName', value: 'id', children: 'children' },
    api: fetchCategoryTree,
  } }

日期选择(ISO 格式)

{ component: 'DatePicker', fieldName: 'deliveryTime', label: $t('xxx.deliveryTime'),
  componentProps: { valueFormat: 'YYYY-MM-DDTHH:mm:ss.SSSZ' } }

日期范围

{ component: 'RangePicker', fieldName: 'createTimeRange', label: $t('common.createTime'),
  componentProps: { format: 'YYYY-MM-DD', valueFormat: 'YYYY-MM-DD' } }

数字输入

{ component: 'InputNumber', fieldName: 'quantity', label: $t('xxx.quantity'),
  rules: 'required', componentProps: { min: 0 } }

隐藏字段(提交但不显示)

{ component: 'Input', fieldName: 'processTags', label: '',
  formItemClass: 'hidden' }

9. Checklist

新建表单弹窗时的检查清单:

  • [ ] 弹窗宽度根据复杂度选择(参见 §2 宽度对照表)
  • [ ] showDefaultActions: false 已设置
  • [ ] 字段排列顺序符合 §4 规范(编码→类型→名称→状态→数值→备注)
  • [ ] Textarea 在表单末尾,rows: 3,双列布局时 col-span-2
  • [ ] 必填字段标注 rules: 'required'(输入)或 rules: 'selectRequired'(下拉)
  • [ ] 所有 label 使用 $t() 国际化
  • [ ] 自动生成字段设置 disabled: true
  • [ ] 有默认值的字段设置 defaultValue
  • [ ] onOpenChange 中先 resetForm() 再判断新建/编辑
  • [ ] onConfirm 中先 validate() 再 lock(),失败时 unlock()
  • [ ] 编辑完成后 emits('success') 通知父组件