Vue3 + Composition API 实战:构建一个通用表单组件系统

107 阅读2分钟

在企业级前端项目中,表单是使用频率非常高的功能模块。为了避免重复开发、提升开发效率,构建一套灵活的“通用表单组件系统”是非常必要的。本文基于 Vue3 和 Composition API,从零实现一个可以动态渲染表单结构的通用方案,并可轻松扩展到多种场景中使用。


🧱 项目结构概览

css
复制编辑
form-system/
├── components/
│   ├── DynamicForm.vue
│   ├── form-items/
│   │   ├── InputItem.vue
│   │   ├── SelectItem.vue
│   │   └── CheckboxItem.vue
├── App.vue
└── main.js

📌 核心目标

  • 支持根据 JSON 配置动态渲染表单项
  • 支持表单校验、默认值回显
  • 支持组件扩展与封装
  • 保持组件逻辑解耦,复用性强

🪄 表单配置示例

js
复制编辑
const formConfig = [
  { type: 'input', label: '姓名', model: 'name', required: true },
  { type: 'select', label: '性别', model: 'gender', options: ['男', '女'] },
  { type: 'checkbox', label: '兴趣', model: 'hobby', options: ['读书', '写作', '编程'] }
]

📄 DynamicForm.vue

vue
复制编辑
<template>
  <form @submit.prevent="submitForm">
    <component
      v-for="item in config"
      :key="item.model"
      :is="getComponent(item.type)"
      v-model="formData[item.model]"
      :item="item"
    />
    <button type="submit">提交</button>
  </form>
</template>

<script setup>
import { reactive, defineProps } from 'vue'
import InputItem from './form-items/InputItem.vue'
import SelectItem from './form-items/SelectItem.vue'
import CheckboxItem from './form-items/CheckboxItem.vue'

const props = defineProps({ config: Array })
const formData = reactive({})

props.config.forEach(item => {
  formData[item.model] = item.type === 'checkbox' ? [] : ''
})

const getComponent = (type) => {
  return {
    input: InputItem,
    select: SelectItem,
    checkbox: CheckboxItem
  }[type]
}

const submitForm = () => {
  console.log('表单数据:', JSON.stringify(formData, null, 2))
}
</script>

📌 示例子组件:InputItem.vue

vue
复制编辑
<template>
  <div>
    <label>{{ item.label }}</label>
    <input v-model="modelValue" />
  </div>
</template>

<script setup>
defineProps(['item', 'modelValue'])
defineEmits(['update:modelValue'])
</script>

其他组件如 SelectItem.vue 和 CheckboxItem.vue 结构类似,可按需封装。


🚀 使用 DynamicForm

vue
复制编辑
<template>
  <DynamicForm :config="formConfig" />
</template>

<script setup>
import DynamicForm from './components/DynamicForm.vue'

const formConfig = [
  { type: 'input', label: '姓名', model: 'name', required: true },
  { type: 'select', label: '性别', model: 'gender', options: ['男', '女'] },
  { type: 'checkbox', label: '兴趣', model: 'hobby', options: ['读书', '写作', '编程'] }
]
</script>

🧩 可扩展性优化建议

  1. ✅ 引入表单验证库(如 vee-validate、Yup)
  2. 🔄 增加双向绑定兼容性(v-model 使用 defineModel)
  3. 📦 增加远程动态 options 的异步支持
  4. 🧱 抽离 schema 类型接口,支持 TS 强类型支持
  5. 📄 结合 Element Plus、Naive UI 等库,实现更美观的表单渲染

✅ 小结

本文完整介绍了一个通用的 Vue3 表单系统实现方案,具有较高的通用性和扩展性,非常适合用于企业管理后台、用户中心、设置中心等模块开发中。