form-create 的 antdv-next 版本:基于 JSON 驱动的 Vue3 低代码动态表单组件实战指南

原创2026-10-14 12:17:071,429 阅读
文章标签:前端低代码UI组件

form-create 的 antdv-next 版本:基于 JSON 驱动的 Vue3 低代码动态表单组件实战指南

导读

@form-create/antdv-next 是 FormCreate 低代码表单生态中面向 Vue 3 + antdv-next(Ant Design Vue 的 next 分支)的适配包,它让开发者用一份 JSON 规则(rule)即可完成表单的动态渲染、数据收集、校验与提交。本指南以该包为主线,先给出安装与接入步骤,再结合仓库源码逐层拆解规则配置、全局配置项、表单操作 API、maker 生成器与底层解析机制,帮助你在政务、OA、ERP 等系统中快速落地可维护的动态表单方案。

一、包定位与核心特性

根据 packages/antdv-next/README.md 的描述,FormCreate 是一个可以通过 JSON 生成具有动态渲染、数据收集、验证和提交功能的低代码表单生成组件,@form-create/antdv-next 就是其中的 antdv-next 版本实现,其 package.json 中的描述为「antdv-next 版本低代码表单」。

该版本具备以下核心能力:

  • JSON 数据驱动:表单的结构、默认值、校验规则、事件全部由 rule 数组描述,天然可序列化、可存储、可远程下发;
  • 可扩展:支持注册任意 Vue 组件与 HTML 标签作为表单字段,内置 20 种常用表单组件;
  • 支持多个 UI 框架:同一套 rule 结构可运行于 element-plus、ant-design-vue、arco-design、naive-ui、tdesign、tiny-vue、vant 等多个适配包;
  • 组件联动:支持字段之间通过 effect/control 等机制相互影响;
  • 丰富的表单操作 API:实例化后返回 fapi,可对表单、字段进行全生命周期操作;
  • 子表单与分组:内置 subForm(object)与 group(数组批量)两类复合结构;
  • 适配移动端、多语言(内置语言包,默认 zh-cn)。

从源码看,该包并非从零实现表单引擎,而是基于 packages/core 核心工厂构建的 UI 适配层。其入口 src/index.js 导出的 FormCreate 对象由 src/core/index.js 中的 antdvNextFormCreate() 通过 FormCreateFactory({ ui, version, manager, install, extendApi, attrs }) 创建,UI 相关的组件注册、解析器、别名、默认配置都在这个包内完成。

二、安装与接入

1. 分支与版本选择

仓库使用多分支维护不同 Vue 大版本(见 README.md 的「分支说明」):

分支 说明
latest Vue 2.0 版本分支
super Vue 2.7 版本分支(功能与 next 分支一致)
next Vue 3.0 版本分支

因此安装 Vue 3 版本时,需要显式使用 @next 标签安装:

npm install @form-create/antdv-next@next

2. 环境依赖

根据 package.json 声明:

  • peerDependencies:vue ^3.5.12,即本包仅适配 Vue 3;
  • devDependencies:antdv-next ^1.2.0,README 明确提示需要将 antdv-next 作为 peer dependency 一起安装:npm install antdv-next;
  • 内部依赖(workspace 包):@form-create/core、@form-create/utils,以及组件包 @form-create/component-antdv-frame(frame 素材选择)、@form-create/component-antdv-group(分组批量)、@form-create/component-antdv-upload(上传)与 @form-create/component-subform(子表单)。

3. 注册到应用

参考 examples/main.js,接入方式如下:

import {createApp} from 'vue'
import 'antdv-next/dist/reset.css'
import FormCreate from './src'
import install from './auto-import'
import App from './App.vue'

FormCreate.use(install);   // 通过 use 应用自动导入的 antdv-next 组件
const app = createApp(App)
app.use(FormCreate)
app.mount('#app')

其中 auto-import.js 会自动注册 antdv-next 的 Button、Form、Input、InputNumber、AutoComplete、Cascader、Checkbox、DatePicker、TimePicker、Radio、Rate、Select、Slider、Switch、Upload、Tree、TreeSelect、Tooltip、Popover、Modal、Col、Row、ColorPicker、Mentions、Transfer 等组件(对每个组件执行 app.component(组件.name) || app.use(组件),避免重复注册)。

也可以直接使用全局属性方式创建表单实例:app.config.globalProperties.$formCreate = $formCreate,或通过组件标签 <form-create :rule="rule" :option="option" v-model="formData" v-model:api="fapi"/> 渲染(见 examples/App.vue)。

三、规则(rule):JSON 描述表单的核心结构

rule 是表单的灵魂。下面结合 examples/rule.js 中的真实示例,讲解最常用的规则字段。

1. 基础字段

{
    type: 'input',                // 组件类型(映射到 antdv-next 组件)
    title: '商品名称',              // 表单项标题
    field: 'goods_name',           // 字段名,作为表单数据的 key
    info: '这个是商品名称',          // 表单项说明(info,默认以 popover 展示)
    value: 'iphone',               // 默认值
    props: {                       // 透传给底层组件的 props
        placeholder: '请输入商品名称',
        disabled: false,
    },
    validate: [                    // 校验规则,透传给 antd Form
        {required: true, message: '请输入商品名称', trigger: 'blur'}
    ]
}
  • type:决定渲染哪个组件,解析逻辑见下文「组件别名与解析器」;
  • field:唯一字段名,value 会同步到 formData[field];
  • props:与 antdv-next 组件 props 一一对应,例如 input 的 placeholder、type: 'password' | 'search',select 的 mode: 'multiple' | 'tags',slider 的 min/max/range,inputNumber 的 step/precision,rate 的 count/allowHalf 等;
  • validate:沿用 antd Form 的校验规则结构(required、min、message、trigger、type: 'array' | 'number' 等),并支持 Promise 形式。

2. 带 options 的选择类字段

radio、checkbox、select 通过 options 声明选项:

{
    type: "radio",
    title: "是否包邮",
    field: "is_postage",
    value: "0",
    options: [
        {value: "0", label: "不包邮", disabled: false},
        {value: "1", label: "包邮", disabled: false},
        {value: "2", label: "未知", disabled: true},
    ]
}

select 的多选、标签模式只需在 props.mode 中切换 multiple / tags,value 相应为数组;checkbox 的 value 同样是数组。从 parsers/checkbox.js 的实现可见:当规则中未显式声明 props.options 时,解析器会自动把顶层 options 合并进 props.options,因此两种写法等价。

3. 日期与时间字段

datePicker 支持多种粒度,均由 props.picker 控制:week(周)、month(月)、quarter(季度)、year(年)、date(默认),区间用 range: true,日期时间区间用 showTime: true,多选用 multiple: true。对应的格式化逻辑在 parsers/datePicker.js:

const FORMAT_TYPE = {
    date: 'YYYY-MM-DD',
    month: 'YYYY-MM',
    week: 'YYYY-wo',
    quarter: 'YYYY-qQ',
    year: 'YYYY',
};
// 未显式指定 valueFormat 时,自动按类型拼接,带 showTime 时追加 ' HH:mm:ss'

timePicker 同理,range: true 切换为时间区间,默认 valueFormat 为 HH:mm:ss(见 parsers/timePicker.js)。

4. 树形与穿梭框

  • treeSelect:props.treeData 传入树数据,支持 allowClear;
  • tree:展示勾选树,props.treeData 定义节点、fieldNames 可映射 key 字段。解析器 parsers/tree.js 会自动将 rule.value 写入 props.checkedKeys 并把 checkable 置为 true,其 modelField 为 checkedKeys;
  • transfer:穿梭框,props.titles 设置左右标题、dataSource 提供数据。解析器 parsers/transfer.js 在未提供 render 时默认渲染 item.title,其 modelField 为 targetKeys(见 modelFields.js)。

5. 对象与分组结构

  • object(子表单):value 为对象,props.rule 声明内部字段,适合把一组字段聚合为一个对象值;
  • group(批量添加):value 为数组,props.rule 声明行内字段,支持 suffix 后缀、max/min、排序、增删,并可在外层 validate 中校验数组本身,如 {required: true, min: 3, type: 'array', message: '最少增加3项', trigger: 'change'}。

这两类复合结构由 @form-create/component-antdv-group(组件源码)与 @form-create/component-subform(组件源码)实现,分别渲染为 fcGroup 与 fcSubForm 组件。

6. 上传与素材选择(frame)

upload 字段直接透传 antdv-next Upload 的 props,如 listType: 'picture-card' | 'text'、action(上传地址)、onSuccess 回调(可在回调中改写 file.url)。

frame 是 FormCreate 特色组件(来自 @form-create/component-antdv-frame),用于素材选择,关键配置(见 rule.js 中 frame 示例):

{
    type: "frame",
    title: "素材",
    field: "fodder",
    value: ["http://form-create.com/logo.png"],
    props: {
        type: "image",      // frame 类型:input / file / image
        src: "../iframe.html", // iframe 地址
        maxLength: 2,       // value 最大数量
        height: "220px", width: "350px",
        spin: false,        // 是否显示加载动画
        title: "请选择",
        handleIcon: true,   // 操作按钮图标,file 类型默认 false,image 默认 true
        allowRemove: true,  // 是否可删除
        onRemove: function () { return false; }, // 删除回调,返回 false 阻止删除
        modal: { fullscreen: true },
    }
}

四、组件别名:type 如何映射到 antdv-next 组件

type 字符串并不直接等于组件名,而是先经过别名映射。映射表定义在 core/alias.js,组件统一加 a 前缀,例如:

  • input → aInput、textarea → aTextarea、search → aInputSearch、inputPassword → aInputPassword
  • select → aSelect、checkbox → aCheckboxGroup、radio → aRadioGroup
  • datePicker → aDatePicker、timePicker → aTimePicker、timeRangePicker → aTimeRangePicker、rangePicker → aRangePicker
  • switch → aSwitch、rate → aRate、slider → aSlider、cascader → aCascader
  • treeSelect → aTreeSelect、transfer → aTransfer、mentions → aMentions、colorPicker → aColorPicker
  • button → aButton、form → aForm、formItem → aFormItem、row → aRow、col → aCol、tooltip → aTooltip、popover → aPopover、icon → aIcon
  • FormCreate 扩展组件:upload → fcUpload、frame → fcFrame、group/array → fcGroup、subForm/object → fcSubForm

从 parsers/input.js 的 render 逻辑可以看出映射的最终落点:textarea/search/password 分别渲染为 aTextarea/aInputSearch/aInputPassword,其余统一为 aInput;而 parsers/datePicker.js 根据 range 是否为 true 选择 rangePicker 或 datePicker。

在 core/index.js 的 install 流程中,这些别名通过 FormCreate.componentAlias(alias) 注册进核心引擎的 CreateNode,从而保证 rule 中书写小写 type 即可命中对应组件。

五、全局配置项(option)

option 控制表单整体行为。默认值定义在 core/config.js:

{
    form: {
        layout: 'horizontal',       // 布局:horizontal / vertical / inline
        labelAlign: 'right',
        labelCol: {flex: '125px'},  // 标签列宽
        wrapperCol: {span: 21},
        validateOnRuleChange: true  // 规则变化时自动触发校验
    },
    row: {gutter: 0},               // 栅格间距
    submitBtn: {
        disabled: false, loading: false,
        type: 'primary', innerText: '', show: true,
        col: undefined, click: undefined
    },
    resetBtn: {
        disabled: false, loading: false,
        type: 'default', innerText: '', show: false,   // 默认不显示
        col: undefined, click: undefined
    }
}

说明:

  • form.layout 切换为 inline 即行内模式(examples/App.vue 中通过 fapi.updateOptions({form: {layout: 'inline'}}) 动态演示);
  • submitBtn / resetBtn 的 click 可自定义按钮点击回调(默认分别触发 fApi.submit() 与 fApi.resetFields(),见 core/manager.js 的 makeSubmitBtn / makeResetBtn);
  • 按钮文字支持多语言:未设置 innerText 时依次取 api.t('submit')、api.t('reset'),兜底为「提交」/「重置」;
  • 类型声明见 types/config.d.ts:除上述结构外,还支持 col、row、info、wrap、title 等布尔或对象形式的布局/说明配置。

六、表单操作 API(fapi)

渲染时通过 v-model:api="fapi" 拿到实例,即可操作表单。除核心引擎在 packages/core/src/frame/api.js 中提供的通用方法(setValue、getValue、append、prepend、removeField、hidden、disabled、display、getRule、fields、resetFields、submit、reload、refresh、updateOptions、toJson、exec、focus、scrollTo、getData/setData 等)外,antdv-next 在 core/api.js 中扩展了与 antd 深度绑定的能力:

API 说明
validate(cb) 校验整个表单(含子表单),失败时触发 validate-fail 事件,返回 Promise
validateField(field, cb) / validateFields(fields, cb) 校验单个/多个字段,字段在子表单中时一并校验
clearValidateState(fields, clearSub) 清空校验状态,可级联清理子表单
clearSubValidateState(fields) 仅清空子表单校验状态
formEl() 获取底层 aForm 组件实例
wrapEl(id) 获取指定字段外层容器实例
submitBtnProps({loading, disabled, show, ...}) / resetBtnProps(...) 动态修改提交/重置按钮属性
btn.loading() / btn.disabled() / btn.show() 提交按钮快捷控制
resetBtn.loading() / ... 重置按钮快捷控制
submit(successFn, failFn) 先校验(validateOnSubmit === false 时跳过),成功后调用 successFn,并触发 submit 事件

例如:

// 动态禁用 goods_name 字段
fapi.disabled(true, 'goods_name');
// 隐藏字段并刷新
fapi.hidden(true, 'goods_name');
// 设置提交按钮 loading
fapi.submitBtnProps({loading: true});
// 在字段后追加新规则
fapi.append({type: 'input', field: 'rule1', title: 'rule1'}, 'goods_name');
// 获取当前规则为 JSON 字符串
fapi.toJson();
// 执行底层组件方法(如 focus)
fapi.exec('goods_name', 'focus');

从 examples/App.vue 可以看到以上 API 的完整演示面板(获取 option/formData/fields、增删规则、字段验证、按钮属性、行内模式切换、提交/重置/刷新等)。

七、maker 生成器:用代码链式构建规则

除了手写 JSON,还可以用 maker 以链式方式生成规则。入口 src/index.js 同时导出 maker。默认 maker 定义在 core/maker.js,并在 parsers/input.js、parsers/datePicker.js 等解析器中追加了专用生成器。完整方法列表见 types/maker.d.ts,常用示例:

maker.input('商品名称', 'goods_name').value('iphone')
      .validate({required: true, message: '请输入商品名称', trigger: 'blur'})
maker.datePicker('活动日期', 'section_day').props({picker: 'month'})
maker.slider('滑块区间', 'slider2').props({min: 0, max: 100, range: true})
maker.selectMultiple('标签', 'tags').options([{value: '1', label: '好用'}])
maker.hidden('hidden_field', value)          // 隐藏字段,见 parsers/hidden.js
maker.frameImageOne('素材', 'fodder')          // 单选 image 类型 frame

便捷别名包括:auto(autoComplete)、number(inputNumber)、time(timePicker)、password(inputPassword)、sliderRange(滑块区间)、selectMultiple(多选)、selectTags(标签多选),以及 frame 系列 frameInputs/frameFiles/frameImages(多选)与 frameInputOne/frameFileOne/frameImageOne(单选)。

八、底层运行原理:install 流程与解析器机制

理解 antdv-next 如何“翻译” rule,是进行二次扩展的关键。核心工厂 FormCreateFactory 位于 packages/core/src/frame/index.js,antdv-next 通过 core/index.js 的 install 钩子完成 UI 层装配:

  1. FormCreate.componentAlias(alias):注册组件别名(aInput 等);
  2. FormCreate.setModelField(k, modelField<a href="https://link.gitcode.com/i/cb5df65242f1fe034165fcf128720a7f" target="_blank">k]):注册 model 字段映射,如 switch → checked、transfer → targetKeys、tree → checkedKeys(见 [core/modelFields.js);
  3. FormCreate.component(name, component):注册 upload、frame、group、subForm 及 QuestionCircleOutlined 图标等组件(components/index.js);
  4. FormCreate.register(required):注册 required 提供器(见 core/provider.js),当规则中 required 值为布尔/字符串/函数/对象时,自动生成基于 Promise 的必填校验,错误消息支持 {{$t.xxx}} 模板与多语言;
  5. FormCreate.parser(parser):逐个注册解析器(parsers/index.js 中的 checkbox、datePicker、rangePicker、hidden、input、timePicker、timeRangePicker、tree、radio、select、row、transfer),每个解析器负责「mergeProp 合并 props」「render 选择具体 VNode」;
  6. FormCreate.maker[name] = makers[name]:挂载 maker 生成器;
  7. 若全局存在 window.antd,自动执行 app.use(window.antd) 完成组件库安装。

解析器(parser)是整个翻译管线的核心单元:以 parsers/checkbox.js 为例,mergeProp 会把顶层 options 合并进 props.options;parsers/row.js 则把 FcRow 渲染为「外层 col(span=24) + 内层 row」的结构,支撑规则里的栅格布局。

此外 core/manager.js 负责渲染编排:为每个字段包一层 aFormItem(含 name、rules、校验触发)、按 col 配置包 aCol、按行配置包 aRow,并统一生成提交/重置按钮(fc-submit-btn / fc-reset-btn),同时兼容 preview 模式(追加 is-preview class)。

九、本地运行示例

仓库提供了可直接运行的示例工程,开发配置见 vite.dev.config.mjs(root 指向 examples 目录,端口 8080):

# 在仓库根目录安装依赖(pnpm workspace)
pnpm install
# 启动 antdv-next 示例(根 package.json 或直接使用 vite 配置)
pnpm dev:antdv-next

示例页面(examples/App.vue + examples/rule.js)内置了 JSON 编辑器(FormData 与 FormOption 双栏联动)、全套 API 操作按钮,以及覆盖输入、选择、日期、上传、frame、树、group、object 等 20 余种字段的演示规则,是理解该包行为的最佳入口。

十、生态与包矩阵

FormCreate 为不同 UI 框架提供同名适配包(各包结构与 antdv-next 一致,均有独立的 examples、src/core、src/parsers、types):

包名 说明
@form-create/antdv-next 本文主题,Vue3 + antdv-next 版本
@form-create/ant-design-vue ant-design-vue 版本
@form-create/element-ui element-plus 版本
@form-create/arco-design arco-design 版本
@form-create/naive-ui naive-ui 版本
@form-create/tdesign tdesign 版本
@form-create/tiny-vue tiny-vue 版本(OpenTiny)
@form-create/vant vant 版本(移动端)
@form-create/designer / @form-create/vant-designer 可视化表单设计器 / 移动端设计器

如需了解其他框架适配包,可直接查看仓库中 packages 目录下对应子包的 README 与源码。

小结

@form-create/antdv-next 的实践价值在于:一份可序列化的 rule JSON,配合全局 option 与强大的 fapi,即可覆盖从简单录入到复杂动态表单(联动、校验、分组、子表单、素材选择)的全部场景;而解析器(parser)+ 组件别名 + modelField 的分层设计,使其既能在 antdv-next 上开箱即用,也能通过注册自定义组件快速扩展。若需在此基础上实现可视化拖拽设计,可进一步探索同一生态的 designer 相关能力(不在本包范围内)。

登录后查看全文
form-create