DgForm 表单组件

基础使用

:::demo

<template>
  <dg-form
    :config="formConf"
    @submit="onFormSubmit"
  >
  </dg-form>
</template>

<script setup lang="ts">
import { ConfigModel } from 'admin-component'
const formConf = reactive<ConfigModel>({
  model: {
    username: ''
  },
  areas: [
    {
      name: 'aboutInput',
      title: '',
      inline: false,
      visiable: true,
      fields: [
        {
          __config__: {
            type: 'text',
            label: 'Username',
            prop: 'username',
            required: true,
            rules: [
              {
                min: 3,
                max: 5,
                message: 'Length should be 3 to 5',
                trigger: 'blur',
              },
            ],
          },
        },
      ],
    },
  ],
})

const onFormSubmit = (v: any) => {
  console.log('submit values:', v)
}
</script>

:::

config 整体配置项

参数类型说明可选值默认值
modelObject表单值-
watch(string | RegExp)[]监听指定prop的 value change,可通过@watch监听回调[]
sizestring全局配置组件的sizedefault,small,largedefault
labelWidthstring | number全局配置labelWidthauto
labelWithColonboolean全局配置是否在label后加冒号-false
labelPositionstring全局配置label位置left,right,topleft
inlineboolean全局配置form-item布局是否为inlinefalse
disabledboolean | ComputedRef<boolean> | Ref<boolean>全局配置disabledfalse
showMessageboolean是否显示校验错误信息false
hideRequiredAsteriskboolean是否隐藏必填的红色星号false
scrollToErrorboolean当校验失败时,滚动到第一个错误表单项false
hideButtonsboolean是否隐藏表单底部默认操作按钮,默认有 提交/重置false
buttons{submit?: {hide?: boolean, text?: string}, reset?: {hide?: boolean, text?: string}}针对表单底部操作按钮提交/重置做显示/文字的配置
areasArray<AreaModel>区域数组,可以把相关表单项划分为一个个区域,样式上的分割-

AreaModel 配置项

用于配置 config.areas = [AreaModel]

参数类型说明可选值默认值
namestring区域名,用作forkey, 请保持值唯一-
titlestring标题名,不需要则设置为空
inlineboolean配置区域内的form-item布局是否inlinefalse
visiableboolean | ComputedRef<boolean> | Ref<boolean>当前区域是否可见
labelWidthstring | number配置区域块内的form-item的labelWidth
labelWithColonboolean配置区域块内的label后是否加冒号false
classNamestring配置区域的classNamefalse
disabledboolean | ComputedRef<boolean> | Ref<boolean>配置区域块内的form-item的disabledfalse
keepboolean当前区域不可见时,提交表单时是否返回当前区域内所有字段的值false
fieldsArray<FieldModel>Field数组,配置各种类型的表单项

FieldModel 配置项

用于配置 config.areas = [{...AreaModel, fields: [FieldModel]}]

参数类型说明可选值默认值
widthstring|number表单项的总宽度
styleObject设置表单项样式
__config__Object一般放置跟form-item相关的属性,如label、rules等false
__config__.propstring表单项的字段名,多级用.分割,如“a.0.c”
__config__.typestring表单项的类型,比如input/单选/多选等,下面会详细介绍
__config__.labelstring表单项的label,非必填
__config__.labelWidthstring | number表单项的labelWidth
__config__.labelWithColonboolean表单项的label后是否加冒号
__config__.visiableboolean | ComputedRef<boolean> | Ref<boolean> | (fieldValue, formValue, prop) => boolean当前表单项是否可见
__config__.requiredboolean | ComputedRef<boolean> | Ref<boolean>表单项是否必填false
__config__.keepboolean表单项不可见时,提交表单时是否返回当前表单项字段的值false
__config__.rulesArray表单项验证rules,rule规则可参考async-validator库
__content__Object一般放置跟input相关的属性,如 placeholder,disabled等,不同类型可设置的属性不一样, 下面会详细介绍
__content__.remarkstring在表单项下方放置描述
__fields__DynamicModel当type: 'dynamic'时,这里配置的是动态数组的配置项
-----
__area__AreaModel插入区域, 相当于嵌套划分区域

注意

__config__[包含其他] 和 __area__ 只能存在其中一个

Input 类型配置项

类型配置

__config__.type = 'text'

该类型的 __content__ 配置项有:

参数类型说明可选值默认值
typestringinput的typetext,textareatext
clearableboolean是否可清除true
disabledboolean | ComputedRef<boolean> | Ref<boolean> | (formValue, prop) => boolean是否disabled
placeholderstringplaceholder请输入${__config__.label}
rowsnumber当input.type=textarea时,显示行数3
prependstring输入框的前缀
appendstring输入框的后缀
$attrsObject具体看el-input的配置项

示例代码:

{
  __config__: {
    type: 'text', 
    label: '普通Input',
    prop: 'inputValue',
  },
  __content__: {
    type: 'textarea',
    rows: 5,
    append: '后缀',
    placeholder: '请输入内容',
  }
}

Number 类型配置项

类型配置

__config__.type = 'number'

该类型的 __content__ 配置项有:

参数类型说明可选值默认值
clearableboolean是否可清除true
disabledboolean | ComputedRef<boolean> | Ref<boolean> | (formValue, prop) => boolean是否disabled
placeholderstringplaceholder请输入${__config__.label}
precisionnumber数值精度2
stepnumber计数器步长1
minnumber最小值
maxnumber最大值
controlsboolean是否使用控制按钮false
$attrsObject具体看el-input-number的配置项

示例代码:

{
  __config__: {
    type: 'number',
    label: '数值输入',
    prop: 'value',
  },
  __content__: {
    controls: true,
  }
}

Select 类型配置项

适用场景:

  • 静态options
  • 异步传入options
  • 远程一次性请求所有options的场景

类型配置

__config__.type = 'select'

该类型的 __content__ 配置项有:

参数类型说明可选值默认值
clearableboolean是否可清除true
disabledboolean | ComputedRef<boolean> | Ref<boolean> | (formValue, prop) => boolean是否disabled
placeholderstringplaceholder请选择${__config__.label}
multipleboolean是否多选
filterableboolean是否可筛选true
loadingboolean | ComputedRef<boolean> | Ref<boolean>是否正在从远程获取数据
optionsArray<{label: string, value: string|number}>选项
api({formValue, prop}) => Promise<options>远程请求api, 适用于一次性加载全部数据
focus() => void当input获得焦点时触发
visibleChange(visible: boolean) => void当下拉框出现/隐藏时触发
$attrsObject具体看el-select的配置项

示例代码:

{
  __config__: {
    type: 'select',
    label: '选择器',
    prop: 'value',
  },
  __content__: {
    // options: optionsRef,
    // loading: loadingRef,
    options: [
      {
        value: 'Option1',
        label: 'Option1',
      },
      {
        value: 'Option2',
        label: 'Option2',
      },
      {
        value: 'Option3',
        label: 'Option3',
      },
      {
        value: 'Option4',
        label: 'Option4',
      },
      {
        value: 'Option5',
        label: 'Option5',
      },
    ]
  },
},
{
  __config__: {
    type: 'select',
    label: '选择器From API',
    prop: 'selectFromApi',
  },
  __content__: {
    api: (v: any) => {
      console.log('Selector From Api', v)
      return new Promise(resolve => {
        setTimeout(() => {
          resolve([
            {
              value: 'Option1',
              label: 'Option1',
            },
            {
              value: 'Option2',
              label: 'Option2',
            },
            {
              value: 'Option3',
              label: 'Option3',
            },
            {
              value: 'Option4',
              label: 'Option4',
            },
          ])
        })
      })
    },
  }
}

SelectRemote 类型配置项

适用于需要远程分页请求options的场景

类型配置

__config__.type = 'selectRemote'

该类型的 __content__ 配置项有:

参数类型说明可选值默认值
clearableboolean是否可清除true
disabledboolean | ComputedRef<boolean> | Ref<boolean> | (formValue, prop) => boolean是否disabled
placeholderstringplaceholder请选择${__config__.label}
api(params) => Promise<{data: any[]}>远程方法
labelKeystringlabel的key
valueKeystringvalue的key
queryKeystring搜索keyword的prop
defaultItemObject
editorItemObject编辑时传入的editorItem
rq
labelSlot
multipleboolean是否多选
listenFullDataSelected(data) => void监听已选择data的回调
$attrsObject具体看dg-selector-remote的配置项

示例代码:

{
  __config__: {
    type: 'selectRemote',
    label: '远程分页选择器',
    prop: 'value',
  },
  __content__: {
    multiple: true,
    api: () => Promise({data: []}),
    labelKey: 'name',
    queryKey: 'name',
    $attrs: {
      collapseTags: true,
    },
  },
}

Date 类型配置项

类型配置

__config__.type = 'date'

该类型的 __content__ 配置项有:

参数类型说明可选值默认值
typestring显示类型具体看el-date-picker的typedate
clearableboolean是否可清除true
disabledboolean | ComputedRef<boolean> | Ref<boolean> | (formValue, prop) => boolean是否disabled
placeholderstringplaceholder请选择${__config__.label}
formatstring显示在输入框中的格式YYYY-MM-DD
valueFormatstring绑定值的格式YYYY-MM-DD
minstring最小日期,若为今天可直接传入'today'
maxstring最大日期,若为今天可直接传入'today'
startPlaceholderstring范围选择时开始日期的占位内容请选择开始时间
endPlaceholderstring范围选择时结束日期的占位内容请选择结束时间
disabledDate(date: string) =>boolean一个用来判断该日期是否被禁用的函数min和max区间(若有传入)
$attrsObject具体看el-date-picker的配置项

示例代码:

{
  __config__: {
    type: 'date',
    label: '选择大于今天的日期',
    prop: 'dateAfterToday',
  },
  __content__: {
    // max: '2022-03-15',
    min: 'today',
    remark: '此处限制选择大于等于今天的日期,max/min是YYYY-MM-DD格式, 为了方便,提供了“today”值使用',
  },
},
{
  __config__: {
    type: 'date',
    label: '选择日期范围',
    prop: 'dateRange',
  },
  __content__: {
    type: 'daterange',
  },
},
{
  __config__: {
    type: 'date',
    label: '选择DateTime',
    prop: 'dateTime',
  },
  __content__: {
    type: 'datetime',
  },
}

Radio 类型配置项

有以下几种UI类型:

  • 普通radio样式
  • button样式
  • 图片样式

类型配置

__config__.type = 'radio'

该类型的 __content__ 配置项有:

参数类型说明可选值默认值
typestringUI类型image,button-
optionsArray<{ value: string; label: string }>选项
disabledboolean | ComputedRef<boolean> | Ref<boolean> | (formValue, prop) => boolean是否disabled
placeholderstringplaceholder请选择${__config__.label}
imageWidthstring图片宽(type=image时适用)100px
imageHeightstring图片高(type=image时适用)140px
imageFitstring图片如何适应容器框(type=image时适用)cover
$attrsObject具体看el-radio的配置项

示例代码:

{
  __config__: {
    type: 'radio',
    label: '普通Radio',
    prop: 'radio',
  },
  __content__: {
    options: [
      {
        value: 'Option1',
        label: 'Option1',
      },
      {
        value: 'Option2',
        label: 'Option2',
      },
      {
        value: 'Option3',
        label: 'Option3',
      },
      {
        value: 'Option4',
        label: 'Option4',
      },
      {
        value: 'Option5',
        label: 'Option5',
      },
    ],
  },
},
{
  __config__: {
    type: 'radio',
    label: 'Radio Button',
    prop: 'radioButton',
  },
  __content__: {
    type: 'button',
    options: [
      {
        value: 'Option1',
        label: 'Option1',
      },
      {
        value: 'Option2',
        label: 'Option2',
      },
      {
        value: 'Option3',
        label: 'Option3',
      },
      {
        value: 'Option4',
        label: 'Option4',
      },
      {
        value: 'Option5',
        label: 'Option5',
      },
    ],
  },
},
{
  __config__: {
    type: 'radio',
    label: 'Radio for Image',
    prop: 'radioImg',
  },
  __content__: {
    type: 'image',
    options: [
      {
        value: 'Option1',
        label:
          'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fww3.sinaimg.cn%2Fmw690%2Fe61e06ccly1gw8d8a7m7yj20u018zq8k.jpg&refer=http%3A%2F%2Fwww.sina.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1647757986&t=f3f1d9b7ae4ef849b23539fb4665776f',
      },
      {
        value: 'Option2',
        label:
          'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fn.sinaimg.cn%2Fsinakd20200409ac%2F289%2Fw690h1199%2F20200409%2Fb300-iryninw7565610.jpg&refer=http%3A%2F%2Fn.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1647755744&t=a6d8f04cbe8433a84f591d0214f2fcc3',
      },
      {
        value: 'Option3',
        label:
          'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201808%2F04%2F20180804234036_FZFQj.thumb.700_0.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1647757902&t=687a56e93ab1ab321fe9dd351bdea262',
      },
      {
        value: 'Option4',
        label:
          'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fnimg.ws.126.net%2F%3Furl%3Dhttp%3A%2F%2Fdingyue.ws.126.net%2F2021%2F0517%2Fc186393ap00qt7rc801gfc000u00190c.png%26thumbnail%3D650x2147483647%26quality%3D80%26type%3Djpg&refer=http%3A%2F%2Fnimg.ws.126.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1647757986&t=622cb5c7a365f1021b7394c3e8ea2648',
      },
      {
        value: 'Option5',
        label:
          'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2Fv2-d6141b49a7f08d02f9ed155c66ad44be_1440w.jpg%3Fsource%3D172ae18b&refer=http%3A%2F%2Fpic1.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1647757986&t=39889a78077959bd648b8e90cad427d1',
      },
    ],
  },
}

Checkbox 类型配置项

类型配置

__config__.type = 'checkbox'

该类型的 __content__ 配置项有:

参数类型说明可选值默认值
optionsArray<{ value: string; label: string }>选项
disabledboolean | ComputedRef<boolean> | Ref<boolean> | (formValue, prop) => boolean是否disabled
$attrsObject具体看el-checkbox的配置项

示例代码:

{
  __config__: {
    type: 'checkbox',
    label: 'Checkbox',
    prop: 'checkbox',
  },
  __content__: {
    options: [
      {
        value: 'Option1',
        label: 'Option1',
      },
      {
        value: 'Option2',
        label: 'Option2',
      },
      {
        value: 'Option3',
        label: 'Option3',
      },
      {
        value: 'Option4',
        label: 'Option4',
      },
      {
        value: 'Option5',
        label: 'Option5',
      },
    ],
  },
}

Cascader 类型配置项

类型配置

__config__.type = 'cascader'

该类型的 __content__ 配置项有:

参数类型说明可选值默认值
propsObject配置选项
optionsObject选项的数据源
showAllLevelsboolean输入框中是否显示选中值的完整路径
clearableboolean是否可清除true
disabledboolean | ComputedRef<boolean> | Ref<boolean> | (formValue, prop) => boolean是否disabled
$attrsObject具体看el-cascader的配置项

示例代码:

{
  __config__: {
    type: 'cascader',
    label: 'Cascader',
    prop: 'cascader',
  },
  __content__: {
    showAllLevels: false,
    props: {
      expandTrigger: 'hover',
    },
    options: [
      {
        value: 'guide',
        label: 'Guide',
        children: [
          {
            value: 'disciplines',
            label: 'Disciplines',
            children: [
              {
                value: 'consistency',
                label: 'Consistency',
              },
              {
                value: 'feedback',
                label: 'Feedback',
              },
              {
                value: 'efficiency',
                label: 'Efficiency',
              },
              {
                value: 'controllability',
                label: 'Controllability',
              },
            ],
          },
        ],
      },
    ],
  },
}

Upload 类型配置项

类型配置

__config__.type = 'upload'

该类型的 __content__ 配置项有:

参数类型说明可选值默认值
acceptstring接受文件类型
listTypestring文件列表的类型(注意:当设为picture时是单个文件,传入值为字符串)text,picture,picture-cardpicture-card
multipleboolean是否支持多选文件true
isCropboolean是否开启剪裁false
stencilPropsObject裁剪比率等相关设置
showFileListboolean是否显示已上传文件列表true
limitnumber最多上传N个文件
disabledboolean | ComputedRef<boolean> | Ref<boolean> | (formValue, prop) => boolean是否disabled
$attrsObject具体看dg-upload的配置项

示例代码:

上传多个图片 示例
{
  __config__: {
    type: 'upload',
    label: 'Upload Images',
    prop: 'uploadImages', //值为数组
  },
  __content__: {},
}
上传单个图片 示例
{
  __config__: {
    type: 'upload',
    label: 'Upload Single Image',
    prop: 'uploadSingle', //值为字符串
  },
  __content__: {
    listType: 'picture',
    showFileList: false,
    multiple: false,
  },
}
上传文件 示例
 {
   __config__: {
    type: 'upload',
    label: 'Upload Files',
    prop: 'uploadFiles', //值为数组
  },
  __content__: {
    listType: 'text',
    accept: '.doc, .docx, .pdf, .xls, .xlsx',
  },
}

纯文本 类型配置项

类型配置

__config__.type = 'plainText'

该类型的 __content__ 配置项有:

参数类型说明可选值默认值
classNameArray<string>文本的className
renderTextStyleObject文本style{}
renderText(value, formValue, prop) => string自定义文本, 支持返回html string(默认显示字段值)

示例代码:

{
  __config__: {
    type: 'plainText',
    label: '纯文本',
    prop: 'plainText1',
  },
  __content__: {
    renderTextStyle: { color: 'blue' },
  },
},
{
  __config__: {
    type: 'plainText',
    label: '纯文本(自定义html)',
    prop: 'plainText1',
  },
  __content__: {
    renderText: (value: string, formValue: any, prop: string) => {
      console.log('renderText', value, formValue, prop)
      return `<div style="color: red; background: yellow;">${value}</div>`
    },
  },
},

自定义组件 类型配置项

类型配置

__config__.type = 'custom'

配置示例代码:

{
  __config__: {
    type: 'custom',
    label: '自定义formItem内容',
    prop: 'customcontet',
  },
}

组件slot示例代码:

<dg-form>
  <template #customcontet="ctx">
    <span style="margin-right: 10px">当前时间: {{ ctx.value || '未获得' }}</span>
    <el-button type="primary" round size="small" @click="() => ctx.setValue(+new Date())">获取当前时间</el-button>
  </template>
</dg-form>

其中 slot 的参数有:

参数类型说明
namestring当前propName
fieldObject当前表单项的配置(即上述的FieldModel)
configObject整个表单的配置
valueany当前表单项的值
setValue(value) => void用于设置当前表单项的值的方法

动态数组 类型配置项

类型配置

__config__.type = 'dynamic'

该类型的 __content__ 配置项有:

参数类型说明可选值默认值
disabledboolean配置数组里所有表单项的disabled

该类型的 __fields__ 配置项有:【即上述的DynamicModel类型】

参数类型说明可选值默认值
itemsArray<FieldModelForDynamic>配置数组Item内的表单项,详情见下方
itemWidthstring数组Item的宽度
inlineboolean[数组Item之间]布局是否inline
itemsInlineboolean数组Item里[表单项之间]布局是否inline
titlestring|(arrayValue, index) => string数组Item的标题
hideTitleboolean是否显示标题false
minnumber至少要有N个
maxnumber最多可添加N个
addBtnTextstring添加按钮文本添加
hideAddBtnboolean是否隐藏添加按钮
hideDeleteBtnboolean是否隐藏删除按钮
initItemDataObject添加时Item给定的默认值{}
extraFieldsstring[]加入指定的其他字段(没有配置在Array Item里的字段, 但需要返回的字段)
keyPropOfItemsstring指定数组Item的某个字段作为for循环的key

其中该类型的 __fields__.items 配置项有:【即上述的FieldModelForDynamic类型】

注意

大体的配置项跟上述的 「FieldModel 配置项」一样,下面只列出不同的配置项

参数类型说明可选值默认值
__config__.visiableboolean | (arrayValue, index, prop) => boolean当前数组Item里的当前表单项 是否可见, 其中arrayValue为数组的值,index为当前位于数组的位置,prop为当前表单项的prop;
__content__.disabledboolean | (arrayValue, index, prop) => boolean当前数组Item里的当前表单项 是否disabled

其他

如果想要整体监听数组某个item的指定prop的value变化,可以配置
watch: ['dynamicEasyArr.0.text', 'dynamicArr.0.projectName']
甚至可以使用Regex监听数组下所有item的指定prop的value的变化,如
watch: [/dynamicArr2.\d+.method$/g]

示例代码:

{
  __config__: {
    type: 'dynamic',
    prop: 'dynamicArr',
  },
  __content__: {
    disabled: false
  },
  __fields__: {
    max: 9,
    min: 1,
    title: (_, index: number) => {
      return `检查项目${index + 1}`
    },
    hideTitle: false,
    inline: false,
    // itemWidth: '40%',
    addBtnText: '添加检查项目',
    initItemData: {
      projectName: '11',
      projectResult: '222',
    },
    items: [
      {
        __config__: {
          type: 'input',
          prop: 'projectName',
          required: true,
          label: '项目名称',
        },
      },
      {
        __config__: {
          type: 'input',
          label: '检查结果',
          prop: 'projectResult',
        },
        __content__: {
          disabled: ((fieldModel: any, index: any, prop: string) => {
            return !fieldModel[index].projectName || dynamicArrDisabled.value
          }) as any,
        },
      },
      {
        __config__: {
          type: 'input',
          label: '备注',
          prop: 'remark',
          required: true,
          visiable: ((fieldModel: any, index: any, prop: any) => {
            return !!fieldModel[index].projectResult
          }) as any,
        },
      },
    ],
  },
}

DEMO 截图: DEMO 截图

Events

名称说明回调参数
watch当config.watch里的props发生value change时触发{ prop: 字段名(具体来说:字段名路径), value: 新值 }
submit提交表单时触发验证通过后formValue(只返回可见字段)
reset重置表单时触发重置后的formValue(只返回可见字段)

Slots

名称说明参数
buttons表单底部增加自定义按钮-
append_${propName}给指定prop添加自定义后缀field: 当前表单项的配置即上述的FieldModel
${propName}自定义组件{name: 当前propName, field: 当前表单项的配置即上述的FieldModel, config: 整个表单的配置, value: 当前表单项的值, setValue: 用于设置当前表单项的值的方法}

方法

名称说明参数返回值
submit提交表单-Promise<formValue>
reset重置表单-Promise<formValue>
Last Updated:
Contributors: mcq