Skip to content

动态表单

在 Vue 项目里,动态表单 是实现 快速 CRUD(增删改查) 的利器。它的核心思想是: 👉 用配置(JSON Schema / 字段配置对象)来驱动表单渲染,而不是手写一堆表单控件。

这样一来:

  • 你只需要维护 字段配置,表单 UI 会自动生成
  • 对于不同的 CRUD 页面,只需要换一份配置,就能生成对应的表单
  • 非常适合后台管理系统 / 低代码场景

✨ 动态表单的关键点

  1. 字段配置(表单项 schema)

    • 字段名
    • 类型(input、select、date、upload…)
    • 校验规则
    • 默认值 / 占位符 / UI 属性
  2. 表单渲染器

    • 根据字段类型选择渲染哪个组件
    • 支持 v-model 双向绑定
    • 支持校验(比如对接 ant-design-vueForm
  3. 增删改查配合

    • 新增:表单为空,提交后新增记录
    • 编辑:表单带初始值,提交后更新记录
    • 查询:表单作为搜索条件
    • 删除:通常配合表格 + 操作按钮

📌 示例:动态表单配置

ts
// formSchema.ts
export const userFormSchema = [
  {
    label: '用户名',
    field: 'username',
    type: 'input',
    required: true,
    placeholder: '请输入用户名',
  },
  {
    label: '性别',
    field: 'gender',
    type: 'select',
    options: [
      { label: '男', value: 'male' },
      { label: '女', value: 'female' },
    ],
    required: true,
  },
  {
    label: '城市',
    field: 'city',
    type: 'input',
    placeholder: '请输入城市',
  },
  {
    label: '生日',
    field: 'birthday',
    type: 'date',
  },
]

📌 Vue 动态表单组件

vue
<template>
  <a-form :model="formModel" layout="vertical">
    <template v-for="item in schema" :key="item.field">
      <a-form-item :label="item.label" :name="item.field" :rules="item.required ? [{ required: true, message: `${item.label}必填` }] : []">
        
        <!-- 根据不同类型渲染 -->
        <a-input
          v-if="item.type === 'input'"
          v-model:value="formModel[item.field]"
          :placeholder="item.placeholder"
        />
        
        <a-select
          v-else-if="item.type === 'select'"
          v-model:value="formModel[item.field]"
          :placeholder="item.placeholder"
        >
          <a-select-option v-for="opt in item.options" :key="opt.value" :value="opt.value">
            {{ opt.label }}
          </a-select-option>
        </a-select>
        
        <a-date-picker
          v-else-if="item.type === 'date'"
          v-model:value="formModel[item.field]"
          style="width: 100%"
        />
      </a-form-item>
    </template>
  </a-form>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { userFormSchema } from './formSchema'

const schema = userFormSchema
const formModel = ref<Record<string, any>>({})
</script>

📌 使用方式

vue
<template>
  <DynamicForm :schema="userFormSchema" v-model="formData" />
  <a-button type="primary" @click="onSubmit">提交</a-button>
</template>

<script setup lang="ts">
import DynamicForm from './DynamicForm.vue'
import { userFormSchema } from './formSchema'
import { ref } from 'vue'

const formData = ref({})

function onSubmit() {
  console.log('表单数据', formData.value)
}
</script>

🔗 CRUD 配合

  • 新增formData = {} → 填写后提交 → 调用 createUser(formData)
  • 编辑formData = rowData → 修改后提交 → 调用 updateUser(id, formData)
  • 搜索formData 作为 query 参数传给接口
  • 删除:配合 a-table操作列 完成

✅ 总结

动态表单让 表单开发从写 UI 转向写配置,是后台管理系统 CRUD 的效率神器。 搭配 ant-design-vue / Element Plus,可以快速做出灵活、可扩展的表单系统。

Released under the MIT License.