Form-create is a form generation component that generates dynamic rendering, data collection, validation, and submission capabilities from JSON. Three UI frameworks are supported and any Vue component can be generated. Built in 20 common form components and custom components, no matter how complex forms can be easily solved.

Document | making | example

Support the UI

  • element-ui
  • iview/view-design
  • ant-design-vue

New features

Version 2.5 has the following major features:

  • Refactor the internal core code
  • Optimized the internal rendering mechanism
  • Optimize internal life cycle events
  • refactoringTypeScript
  • newnextTickMethod to set the post-render callback
  • Added support for paging loading components to speed up the first screen rendering
  • Added user-defined configuration itemseffect
  • New Support for Modificationtype
  • newcontrolYou can configure the position for inserting rules
  • To optimize thecontrolThose that meet the conditions will take effect. The previous version can only take effect for the first one
  • Added support for component prefix suffixesprefix.suffix
  • newupdateThe configuration,valueTriggered after sending changes
  • Additional supportwrapConfiguration item, configurationFormItem
  • newobjectcomponent
  • Added support for customizationtitle.infocomponent
  • Added rich text componentwangEditor
  • Added native event support for event injection
  • supportvalue.syncGets the bidirectional bindingformData
  • Optimize the default form submission button

The installation

Install the corresponding version according to the UI you use

Element – UI version

npm i @form-create/element-ui
Copy the code

[email protected] | 3. X version

npm i @form-create/iview
Copy the code

Iview/[email protected] version

npm i @form-create/iview4
Copy the code

[email protected] + version

npm i @form-create/ant-design-vue
Copy the code

Quick learning

This article uses element-UI as an example

  1. Write the following in main.js:
import Vue from 'vue'
import ELEMENT from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

import formCreate from '@form-create/element-ui'

Vue.use(ELEMENT)
Vue.use(formCreate)
Copy the code
  1. To generate the form

Online sample

<template>
  <div id="app1">
      <form-create v-model="fApi" :rule="rule" :option="option" :value.sync="value"></form-create>
  </div>
</template>
Copy the code
export default {
    data() {
        return {
            // Instance object
            fApi: {},
            // Form data
            value: {},
            // Form generation rules
            rule: [{type: 'input'.field: 'goods_name'.title: 'Trade Name'
                },
                {
                    type: 'datePicker'.field: 'created_at'.title: 'Creation time'}].// Configure component parameters
            option: {
                // Form submission event
                onSubmit: function (formData) {
                    alert(JSON.stringify(formData))
                }
            }
        }
    }
}

Copy the code

Rules is introduced

type

  • type: String
  • Description: Set the name of the generated component

field

  • type: String
  • Note: Set the field name of the form component, custom components can not be configured

title

  • type: String|Object
  • Description: Name of the component

value

  • type: any
  • Description: The field value of the form component, custom components can not be set

props

  • parameter: Object
  • instructions: sets the componentprops

info

  • type: String|Object
  • Note: Set the prompt information of the component

hidden

  • type: Bool
  • Description: Sets whether the component is rendered

prefix

  • type: string|Object
  • Description: Set the component prefix

suffix

  • type: string|Object
  • Description: Set the suffix of the component

validate

  • type: Array
  • Description: Set validation rules for form components

options

  • type: Array
  • instructionsSet:radio.select.checkboxComponents such asoptionThe option

col

  • type: Object
  • Description: Set layout rules for components

control

  • type: Object
  • Control the display of other components

children

  • Type: Array rule | < string | maker >

  • Note: Set the slot for the parent component. The default value is default. This parameter can be used with the slot configuration item

    • Example 1
    formCreate.maker.create('button').children([
       'Button contents' 
    ])
    Copy the code
    • Example 2
    maker.input('text'.'text'.'text').children([
        maker.create('span').children(['append']).slot('append')])Copy the code
    • Example 3
    formCreate.maker.create('i-row').children([
      formCreate.maker.create('i-col').props('span'.12).children([
        formCreate.maker.template(' Custom component '.() = > new Vue)
      ]),
    ])
    Copy the code

Function is introduced

1. Customize components

Form-create supports generating any VUE component inside the form

Online sample

For example, generate an el-Button component:

{
	// Type can be a built-in component name, a vUE component name or an HTML tag
	type: 'el-button'./ /...
	children: ['Button contents']}Copy the code

Generate an HTML tag

{
	// Type can be a built-in component name, a vUE component name or an HTML tag
	type: 'span'./ /...
	children: ['span content']}Copy the code

Attention! The generated component must be mounted globally or via form-create

Mount via Vue

Vue.component(component.name, component);
Copy the code

Mount via form-create

formCreate.component(component.name, component);
Copy the code

2. Customize the layout

By setting configuration itemscolOr raster components can implement the layout of components

Online sample

The component layout is set through the col configuration item to show two components on a single line

[{type:'input'.field:'input1'.title:'input1'.col: {span:12}
	},{
        type:'input'.field:'input2'.title:'input2'.col: {span:12}},]Copy the code

Set the grid component to show three components in a row

{
	type:'el-row'.children: [{type:'el-col'.props: {span:8
        	},
        	children: [{type:'input'.field:'input1'.title:'input1'}]}, {type:'el-col'.props: {span:8
        	},
        	children: [{type:'input'.field:'input1'.title:'input1'}]}, {type:'el-col'.props: {span:8
        	},
        	children: [{type:'input'.field:'input1'.title:'input1'}}}]]Copy the code

3. Component prefixes

Configure the prefixes of components by generating the prefix attribute of the rule, and configure the suffixes of components by generating the suffix attribute

Online sample

{
    type:'input'.field:'text'.title:'text'.prefix:'prefix'.suffix:'suffix',}Copy the code

Set the prefix and suffix to custom components

{
    type:'input'.field:'text'.title:'text'.value:'default'.prefix: {type:'ElButton'.children: ['prefix']},suffix: {type:'ElButton'.children: ['suffix']}}Copy the code

4. Component linkage

The control configuration item enables you to control whether or not other components are displayed from the value of the component

Online sample

For example, if the rating is less than 3 stars, enter the reason for the poor rating

{
    type:'rate'.field: 'star'.title:'score'.value:5.control:[
        {
            handle(val){
                return val < 3
            },
            rule:[
                {
                    type:'input'.field:'info'.title:'Reasons for bad reviews'.value:'default info',}]}]}Copy the code
parameter instructions type
value When the component values andvalueIsochronous displayruleThe components in the string|Number|Bool
handle whenhandleMethod returnstrueDisplayed whenruleThe components in the Function
rule This component controls the components that are displayed Array
append Set up theruleThe position to append the rule to in string
prepend Set up theruleThe position where the rule is pre-inserted in string
child Set up theruleWhether to insert into children of the specified position. By default, to children of the current rule Boolean

Attention!handlePriority greater thanvalue, all eligiblecontrolWill take effect

5. Form validation

Validation rules for components can be set through the validate configuration item, and validation is also supported for custom form components

Online sample

For example, set the input component to mandatory

{
	type:'input'./ /...
	validate: [{required:true.type:'string'.message:'Please input content'}}]Copy the code
parameter instructions type The default value
enum Enumerated type string
len The length of the field number
max The maximum length number
message Check copy string
min Minimum length number
pattern Regular expression check RegExp
required Whether the choice boolean false
transform Convert field values before validation function(value) => transformedValue:any
type Built-in checksum type,optional string ‘string’
validator Custom check function(rule, value, callback)
whitespace If this parameter is mandatory, whether Spaces are considered errors boolean false

Attention! Type needs to be defined according to the value type of the component

The APi is introduced

The following are common methods

Complete Api introduction

Setting form values

Overwrite, undefined fields are set to NULL

type coverValue = (formData:{[field:string] :any}) = > void
Copy the code
  • Usage:
fApi.coverValue({goods_name:'HuaWei'})
Copy the code

Merge mode. Undefined fields are not modified

interface setValue {
    (formData:{[field:string] :any}) :void
    (field:string.value:any) :void
}
Copy the code
  • Usage:
fApi.setValue({goods_name:'HuaWei'})
Copy the code

Alias methods changeValue, changeField

Hidden fields

interface hidden {
    // Hide all components
    (status:Boolean) :void
    // Hide the specified component
    (status:Boolean.field:string) :void
    // Hide some components
    (status:Boolean.field:string[]) :void 
}
Copy the code
  • Usage:
fApi.hidden(true.'goods_name')
Copy the code

Gets the component hidden state

type hiddenStatus = (field:string) = >Boolean
Copy the code
  • Usage:
const status = fApi.hiddenStatus('goods_name')
Copy the code

Access rules

interface getRule {
    (field:string):Rule
    (field:string.origin: true): FormRule
}
Copy the code
  • Usage:
const rule = fApi.getRule('goods_name')
Copy the code

Insert the rules

The front insert

interface prepend {
    // Insert the first one
    (rule:FormRule):void 
    // Insert before the specified field
    (rule:FormRule, field:string) :void
    // Insert into the specified field children
    (rule:FormRule, field:string.child:true) :void
}
Copy the code
  • Usage:
fApi.prepend({
     type:"input".title:"Product Profile".field:"goods_info".value:"".props: {
         "type": "text"."placeholder": "Please enter product description",},validate:[
         { required: true.message: 'Please enter product description'.trigger: 'blur'},],},'goods-name')
Copy the code

The rear additional

interface append {
    // Insert the last one
    (rule:FormRule):void 
    // Insert after the specified field
    (rule:FormRule, field:string) :void
    // Insert into the specified field children
    (rule:FormRule, field:string.child:true) :void
}
Copy the code
  • Usage:
fApi.append({
     type:"input".title:"Product Profile".field:"goods_info".value:"".props: {
         "type": "text"."placeholder": "Please enter product description",},validate:[
         { required: true.message: 'Please enter product description'.trigger: 'blur'},],},'goods-name')
Copy the code

Deleting a specified rule

type removeRule = (rule:FormRule) = > FormRule
Copy the code
  • Usage:
const rule = {type:'input'./ * *... * * /}
fApi.removeRule(rule)
Copy the code

Validate form

type validate = (callback:(... args:any[]) = >void) = > void
Copy the code
  • Usage:
fApi.validate((valid, fail) = > {
    if(valid){
        // Todo form validates
    }else{
        // Todo form validation failed}})Copy the code

Validate specified fields

type validateField = (field, callback:(... args:any[]) = >void) = > void
Copy the code
  • Usage:
fApi.validateField('goods_name'.(valid, fail) = > {
    if(valid){
        // Todo field validates
    }else{
        // Todo field validation failed}})Copy the code

Get form data

interface formData {
    // Get all data
    (): {[field:string] :any }
    // Get the data of some fields
    (field:string[]): {[field:string] :any}}Copy the code
  • Usage:
const formData = fApi.formData()
Copy the code

Modify submit button

type submitBtnProps = (props:Object) = > void
Copy the code
  • Usage:
fApi.submitBtnProps({disabled:true})
Copy the code
  • Quick operation:

    • fApi.btn.loading(true)Set the commit button to loading
    • fApi.btn.disabled(true)Disable the submit button
    • fApi.btn.show(true)Set the display status of the submit button

Modify reset button

type resetBtnProps = ( props:Object) = > void
Copy the code
  • Usage:
fApi.resetBtnProps({disabled:true})
Copy the code
  • Quick operation:

    • fApi.resetBtn.loading(true)Set the reset button to loading
    • fApi.resetBtn.disabled(true)Disable the reset button
    • fApi.resetBtn.show(true)Set reset button display status

Hidden form

type hideForm = (hide:Boolean) = >void
Copy the code
  • Usage:
fApi.hideForm(true)
Copy the code

Submit the form

type submit = (success: (formData: FormData, $f: fApi) => void, fail: ($f: fApi) => void) = > void
Copy the code
  • Usage:
fApi.submit((formData, fapi) = > {
    // Todo submits the form
},() = >{
    // Todo form validation failed
})
Copy the code