Skip to content

API Overview

FormCreate provides a comprehensive set of API interfaces that give developers full control over forms at every stage, including form generation, dynamic updates, validation, and data processing. These APIs make it easy to implement complex form requirements.

Getting API

FormCreate provides multiple ways to obtain the API object, enabling developers to operate and manage forms in different scenarios.

Global Method

You can generate a form and obtain the API object directly using the create method. This method is ideal for non-component scenarios, such as generating forms in separate script files.

js
const api = formCreate.create(rules)

Component Mode

In Vue components, bind the api object using v-model:api to operate the form within the component.

vue
<form-create name="form" :rule="rules" v-model:api="api"></form-create>

Example: Using the API in a Vue component for dynamic form operations:

vue
<template>
  <form-create name="form" :rule="rules" v-model:api="api"></form-create>
</template>


<script setup>
const rules = ref([
  { type: 'input', field: 'username', title: 'Username', props: { placeholder: 'Please enter username' } },
  { type: 'input', field: 'email', title: 'Email', props: { placeholder: 'Please enter email' } },
  { type: 'input', field: 'password', title: 'Password', props: { type: 'password', placeholder: 'Please enter password' } },
]);
const api = ref(null);
onMounted(() => {
  // Use API for operations
  api.value.setValue('username', 'example_user');
});
</script>

You can also use the getApi method to obtain the API object from anywhere, such as in other components:

js
const api = formCreate.getApi('form')

Event Injection

In form event handlers, the API object is automatically injected through event parameters. This approach works well for handling form interaction events.

ts
type InjectArg = {
    api: API,// Form API object
    rule: Rule[],// Form generation rules
    self: Rule,// Current component generation rule
    option: Object,// Form global configuration
    inject: Any,// Custom injected parameters
    args: any[],// Original callback parameters
}

Example: Obtaining the API object and performing operations in the blur event of a form component:

js
const rule = {
  type: 'input',
  field: 'inputField',
  title: 'Input Field',
  inject: true,
  on: {
    blur(inject) {
      console.log(inject.api);  // Get API object
      inject.api.setValue('inputField', 'blurred');
    }
  }
}

Custom Component Injection

When generating custom components, FormCreate automatically injects useful parameters into the component. Access these via props.formCreateInject.

  • The formCreateInject object contains the following properties:
    • formCreateInject.api Form API object for operating the form.
    • formCreateInject.options Global configuration of the form component.
    • formCreateInject.rule Generation rule object that defines all configurations of the component.
    • formCreateInject.field Field name bound to form data.

Example: Using the formCreateInject object in a custom component for operations:

js
const customComponent = defineComponent({
  name: 'custom-component',
  props: {
    formCreateInject: Object, // Automatically injected form parameters
  },
  mounted() {
    console.log(this.formCreateInject.api);  // Access API inside the component
  }
});

Note

Parent forms and sub-forms, as well as sub-forms themselves, are independent of each other. When operating, call the API for each form. Obtain the operation interface for a specified sub-form using the getSubForm method.

API Function Description

Api Properties

Property NameTypeDescription
configOptionsGlobal configuration object of the form
indexnumber|undefinedIndex of the current form in the sub-form
siblingsApi[]|undefinedAPI array of sibling forms
ruleRule[]Generation rule list of the current form
formObjectData object of the current form
parentApi|undefinedAPI object of the parent form
topApi|undefinedAPI object of the top-level form
childrenApi[]API object array of sub-forms

Api Methods

Button Control Methods

Method NameParametersReturn ValueDescription
btn.loadingloading: booleanvoidSet submit button loading state
btn.disableddisabled: booleanvoidSet submit button disabled state
btn.showshow: booleanvoidSet submit button display state
resetBtn.loadingloading: booleanvoidSet reset button loading state
resetBtn.disableddisabled: booleanvoidSet reset button disabled state
resetBtn.showshow: booleanvoidSet reset button display state
submitBtnPropsprops: ButtonPropsvoidUpdate submit button configuration
resetBtnPropsprops: ButtonPropsvoidUpdate reset button configuration

Element Operation Methods

Method NameParametersReturn ValueDescription
elid: stringanyGet DOM element or Vue instance of the specified component
formEl-ComponentInternalInstance|undefinedGet Vue component instance of the entire form
wrapElid: stringComponentInternalInstance|undefinedGet Vue component instance of the specified form item

Data Operation Methods

Method NameParametersReturn ValueDescription
formData-ObjectGet current form data object
formDatafield: string[]ObjectGet data of specific fields
getValuefield: stringanyGet value of the specified field
coverValueformData: ObjectvoidOverwrite current form values with new data
setValueformData: ObjectvoidSet values for the entire form
setValuefield: string, value: anyvoidSet value of a specific field

Form Structure Operation Methods

Method NameParametersReturn ValueDescription
removeFieldfield: stringRuleRemove component by field name
removeRulerule: RuleRuleRemove component by rule
fields-string[]Get all field names
appendrule: RulevoidAppend new component
appendrule: Rule, field: stringvoidAppend component after specified field
appendrule: Rule, field: string, child: booleanvoidAppend child component after specified field
prependrule: RulevoidInsert new component at the beginning
prependrule: Rule, field: stringvoidInsert component before specified field
prependrule: Rule, field: string, child: booleanvoidInsert child component before specified field

Display Control Methods

Method NameParametersReturn ValueDescription
hiddenhidden: BooleanvoidHide/show form component (no DOM)
hiddenhidden: Boolean, field: string|Array<string>voidHide/show specified component
displayhidden: BooleanvoidControl component display (with DOM)
displayhidden: Boolean, field: string|Array<string>voidControl specified component display
hiddenStatusfield: StringBooleanGet component hidden state
displayStatusfield: StringBooleanGet component display state
disableddisabled: BooleanvoidDisable/enable form component
disableddisabled: Boolean, field: string|Array<string>voidDisable/enable specified component

Rule Operation Methods

Method NameParametersReturn ValueDescription
model-{ [field: string]: Rule }Get form component generation rules
component-{ [name: string]: Rule }Get all component rules with name attribute defined
reloadrules: Rule[]voidReload form rules
updateOptionsoptions: OptionsvoidUpdate form global configuration
updateRulefield: string, rule: RulevoidUpdate specified field rule
updateRulerules: { [field: string]: Rule }voidBatch update field rules
mergeRulefield: string, rule: RulevoidMerge specified field rule
mergeRulesrules: { [field: string]: Rule }voidBatch merge field rules
getRuleid: stringRuleGet specified field rule
getRuleid: string, origin: trueRuleGet original rule
getRuleid: string, origin: falseRuleGet processed rule
findTypetype: stringRuleGet rule by component type
findTypestype: stringRule[]Get multiple rules by component type
getCurrentFormRule-RuleGet current sub-form rule
getRenderRuleid: stringRuleGet component final rendering rule
getRefRuleid: stringRule|Rule[]Get rule by name attribute
getParentRuleid: string|RuleRule|undefinedGet parent rule
Method NameParametersReturn ValueDescription
updateValidateid: string, validate: Object[], merge?: BooleanPromise<any>Update component validation rules
updateValidatesvalidates: { [id: string]: Object[] }, merge?: BooleanPromise<any>Batch update validation rules
refreshValidate-voidRefresh form validation state
clearValidateStatefields?: string|string[], clearSub?: BooleanvoidClear validation state
clearSubValidateStatefields?: string|string[]voidClear sub-form validation state
validatecallback?: (state: any) => voidPromise<any>Validate entire form
validateFieldfield: string, callback?: (state: any) => voidPromise<any>Validate specified field

Component Operation Methods

Method NameParametersReturn ValueDescription
methodid: string, name: string(...args: any[]) => anyGet component method
execid: string, name: string, ...args: any[]anyExecute component method
triggerid: string, event: string, ...args: any[]voidTrigger component event

Form Operation Methods

Method NameParametersReturn ValueDescription
onSubmitfn: (formData: Object, api: Api) => voidvoidListen to form submit event
submitsuccess?: (formData: Object, api: Api) => void, fail?: (api: Api) => voidPromise<any>Manually submit form
syncfield: string|string[]voidSync specified field
syncrule: Rule|Rule[]voidSync specified rule
refresh-voidRe-render entire form
refreshOptions-voidRefresh form options
hideFormhide?: BooleanvoidHide entire form
changeStatus-BooleanGet form modification state
clearChangeStatus-voidReset form modification state
toJsonspace?: string|numberstringGet form JSON rules
closeModalid: stringvoidClose frame component popup
resetFields-voidReset entire form
resetFieldsfield: string|string[]voidReset specified field
getSubFormfield: stringApi|Api[]Get sub-form API object

Async Operation Methods

Method NameParametersReturn ValueDescription
nextTickfn: (api: Api) => voidvoidExecute callback after form rendering
nextRefreshfn: FunctionvoidRe-render form after callback
deferSyncValuefn: Function, autoSync?: booleanvoidSync form data after callback

Data Management Methods

Method NameParametersReturn ValueDescription
fetchopt: FetchOptionPromise<any>Send remote request
setDataid: string, value?: anyvoidSet external data
getDataid: string, defaultValue?: anyanyGet external data
watchDatafn: (get: (id: string, defaultValue?: any) => any, change: boolean) => void() => FunctionWatch data changes
refreshDataid: stringvoidRefresh components related to external data

Event Management Methods

Method NameParametersReturn ValueDescription
bus.$emitevent: string, ...args: any[]voidManually trigger event
bus.$onevent: string|string[], callback: FunctionvoidListen to event
bus.$onceevent: string|string[], callback: FunctionvoidListen to one-time event
bus.$offevent: string|string[], callback: FunctionvoidCancel event listener
emitevent: string, ...args: any[]voidTrigger form custom event
onevent: string|string[], callback: FunctionthisListen to form custom event
onceevent: string|string[], callback: FunctionthisListen to one-time form event
offevent?: string|string[], callback?: FunctionthisCancel form event listener

Custom Property Methods

Method NameParametersReturn ValueDescription
setEffectid: string, attr: string, value: anyvoidSet custom property
clearEffectDataid: string, attr?: stringvoidClear custom property data
Data Structure

The following is a concise explanation of the complete data structure of the Api and its available methods:

ts
interface Api {
  // Global configuration object of the form, containing all form configuration information
  readonly config: Options;
  readonly options: Options;
  // Get the index of the current form in the sub-form (group) (if the form is a nested sub-form)
  readonly index: number|undefined;
  // Get all form APIs in the sub-form (group) where the current form is located (if the form is a nested sub-form)
  readonly siblings: Api[]|undefined;
  // Generation rule list of the current form, defining the structure and components of the form
  readonly rule: Rule[];
  // Data object of the current form, containing values of all fields
  readonly form: Object;
  // API object of the parent form (if the form is a nested sub-form)
  readonly parent: Api | undefined;
  // API object of the top-level form (applicable to nested form scenarios)
  readonly top: Api | undefined;
  // API object array of sub-forms, allowing operations on nested sub-forms
  readonly children: Api[];
  // Control interface for submit button, allowing dynamic setting of submit button state
  btn: {
    // Set the loading state of the submit button, such as loading state
    loading(loading: boolean): void;
    // Set the disabled state of the submit button
    disabled(disabled: boolean): void;
    // Set the display state of the submit button, controlling whether the button is visible
    show(show: boolean): void;
  }
  // Control interface for reset button, allowing dynamic setting of reset button state
  resetBtn: {
    // Set the loading state of the reset button
    loading(loading: boolean): void;
    // Set the disabled state of the reset button
    disabled(disabled: boolean): void;
    // Set the display state of the reset button
    show(show: boolean): void;
  }
  // Get DOM element or Vue instance of the specified component
  el(id: string): any;
  // Get Vue component instance of the entire form, convenient for directly operating internal methods or properties of the component
  formEl(): undefined | ComponentInternalInstance;
  // Get Vue component instance of the specified form item, used for operations on specific form items
  wrapEl(id: string): undefined | ComponentInternalInstance;
  // Update configuration of form submit button, such as text, style, etc.
  submitBtnProps(props: ButtonProps): void;
  // Update configuration of form reset button
  resetBtnProps(props: ButtonProps): void;
  // Get data object of the current form, returning values of all fields
  formData(): Object;
  // Get data of specific fields, returning values of specified fields
  formData(field: string[]): Object;
  // Get value of the specified field
  getValue(field: string): any;
  // Overwrite current form values with new data
  coverValue(formData: Object): void;
  // Set form values, can set for the entire form or for specific fields
  setValue(formData: Object): void;
  setValue(field: string, value: any): void;
  // Remove corresponding component by field name
  removeField(field: string): Rule;
  // Remove corresponding component by component generation rule
  removeRule(rule: Rule): Rule;
  // Get names of all fields in the form
  fields(): string[];
  // Append new component after specified field
  append(rule: Rule): void;
  append(rule: Rule, field: string): void;
  append(rule: Rule, field: string, child: boolean): void;
  // Insert new component before specified field
  prepend(rule: Rule): void;
  prepend(rule: Rule, field: string): void;
  prepend(rule: Rule, field: string, child: boolean): void;
  // Hide or show specified component of the form (no DOM node)
  hidden(hidden: Boolean): void;
  hidden(hidden: Boolean, field: string | Array<string>): void;
  // Control display of form component (with DOM node)
  display(hidden: Boolean): void;
  display(hidden: Boolean, field: string | Array<string>): void;
  // Get hidden state of component, returns boolean value
  hiddenStatus(field: String): Boolean;
  // Get display state of component, returns boolean value
  displayStatus(field: String): Boolean;
  // Disable or enable specified component of the form
  disabled(disabled: Boolean): void;
  disabled(disabled: Boolean, field: string | Array<string>): void;
  // Get generation rules of all form components, returns an object with field names as keys and rule objects as values
  model(): { [field: string]: Rule };
  // Get all component rules with `name` attribute defined, returns an object with component names as keys and rule objects as values
  component(): { [name: string]: Rule };
  // Reload form, replace current form rules with new rule list
  reload(rules: Rule[]): void;
  // Update global configuration of the form
  updateOptions(options: Options): void;
  // Listen to form submit event, execute callback when form is submitted
  onSubmit(fn: (formData: Object, api: Api) => void): void;
  // Manually submit form, trigger submit process and execute success or failure callback
  submit(success?: (formData: Object, api: Api) => void, fail?: (api: Api) => void): Promise<any>;
  // Sync specified field or rule, ensure form state is synchronized with latest data
  sync(field: string | string[]): void;
  sync(rule: Rule | Rule[]): void;
  // Re-render entire form, suitable for updating form layout or content
  refresh(): void;
  refreshOptions(): void;
  // Hide entire form, usually used when form does not need to be displayed
  hideForm(hide?: Boolean): void;
  // Get modification state of the form, returns boolean value
  changeStatus(): Boolean;
  // Reset modification state of the form
  clearChangeStatus(): void;
  // Set custom property, used for extending form functionality
  setEffect(id: string, attr: string, value: any): void;
  // Clear data of custom property
  clearEffectData(id: string, attr?: string): void;
  // Update form generation rule of specified field
  updateRule(field: string, rule: Rule): void;
  updateRule(rules: { [field: string]: Rule }): void;
  // Merge form generation rule of specified field
  mergeRule(field: string, rule: Rule): void;
  mergeRules(rules: { [field: string]: Rule }): void;
  // Get generation rule of specified field
  getRule(id: string): Rule;
  getRule(id: string, origin: true): Rule;
  getRule(id: string, origin: false): Rule;
  //Get generation rule by component type
  findType(type: string): Rule;
  findTypes(type: string): Array<Rule>;
  //If the current form is a sub-form, get the sub-form component rule using this method
  getCurrentFormRule(): Rule;
  // Get final rendering rule of component, containing content after dynamic changes
  getRenderRule(id: string): Rule;
  // Get component rule by `name` attribute, supports single or multiple components
  getRefRule(id: string): Rule | Rule[];
  // Get parent rule by `name`, `field` or rule
  getParentRule(id: string | Rule): undefined | Rule;
  // Update validation rules of component, supports merge or replace
  updateValidate(id: string, validate: Object[], merge?: Boolean): Promise<any>;
  updateValidates(validates: { [id: string]: Object[] }, merge?: Boolean): Promise<any>;
  // Refresh validation state of the form, re-trigger validation logic
  refreshValidate(): void;
  // Clear validation state of specified field or entire form
  clearValidateState(fields?: string | string[], clearSub?: Boolean): void;
  // Clear validation state of sub-form of specified field
  clearSubValidateState(fields?: string | string[]): void;
  // Validate form, returns Promise of validation result
  validate(callback?: (state: any) => void): Promise<any>;
  // Validate specified field, returns Promise of validation result
  validateField(field: string, callback?: (state: any) => void): Promise<any>;
  // Get method of specified component, used for calling custom methods of component
  method(id: string, name: string): (...args: any[]) => any;
  // Manually execute method of specified component
  exec(id: string, name: string, ...args: any[]): any;
  // Manually trigger event of component, suitable for simulating user operations or triggering custom logic
  trigger(id: string, event: string, ...args: any[]): void;
  // Get JSON generation rules of form, used for exporting or saving form structure
  toJson(space?: string | number): string;
  // Close popup of specified frame component
  closeModal(id: string): void;
  // Reset form, reset values of all fields to initial state
  resetFields(): void;
  resetFields(field: string | string[]): void;
  // Get sub-form API object of specified field, supports nested form operations
  getSubForm(field: string): Api | Api[];
  // Execute callback after form rendering, ensure all components are loaded
  nextTick(fn: (api: Api) => void): void;
  // Re-render form after executing callback, suitable for form refresh after dynamic updates
  nextRefresh(fn: Function): void;
  // Sync form data after executing callback, ensure data is synchronized with UI
  deferSyncValue(fn: Function, autoSync?: boolean): void;
  // Send remote request, supports custom request logic and processing methods
  fetch(opt: FetchOption): Promise<any>;
  // Set external data, supports using external data sources in forms
  setData(id: string, value?: any): void;
  // Get external data, returns previously set data object
  getData(id: string, defaultValue?: any): any;
  // Read external data through get method in callback, get change listener for data, re-trigger callback when data changes. Returns unsubscribe function
  watchData(fn: (get: (id: string, defaultValue?: any) => any, change: boolean) => void): () => Function;
  // Refresh components related to external data, ensure UI is synchronized after data changes
  refreshData(id: string): void;
  // Built-in event management system, supports manual triggering and listening to custom events
  bus: {
    $emit(event: string, ...args: any[]): void;  // Manually trigger event
    $on(event: string | string[], callback: Function): void;  // Listen to event
    $once(event: string | string[], callback: Function): void;  // Listen to one-time event
    $off(event: string | string[], callback: Function): void;  // Cancel event listener
  };
  // Manually trigger custom event of form
  emit(event: string, ...args: any[]): void;
  // Listen to form custom event
  on(event: string | string[], callback: Function): this;
  // Listen to one-time form custom event
  once(event: string | string[], callback: Function): this;
  // Cancel listener of form custom event
  off(event?: string | string[], callback?: Function): this;
}

API Extension

FormCreate's API has high extensibility, allowing developers to create custom operations and functions to meet complex business requirements.

Example: Extending API to implement custom operations

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


formCreate.extendApi((api) => {
  api.customMethod = function() {
    // Execute custom operation
    console.log('This is a custom API method');
  }
})

Through the extendApi method, you can add new methods or properties to make the API more suitable for specific business requirements. This approach is very suitable for personalized API customization in large projects.

Examples

Disable Form

vue
<template>
    <div>
        <form-create :v-model:api="api"/>
        <el-button @click="handle">Disable Form</el-button>
    </div>
</template>
<script setup>
    import {ref} from 'vue';
    const api = ref(null);
    function handle() {
        api.value.disabled(true);
    }
</script>

Modify Component Value

vue
<template>
    <div>
        <form-create :v-model:api="api"/>
        <el-button @click="handle">Disable Form</el-button>
    </div>
</template>
<script setup>
    import {ref} from 'vue';
    const api = ref(null);
    function handle() {
        api.value.setValue({
            field: 'value'
        });
    }
</script>

Get Component Rule

vue
<template>
    <div>
        <form-create :v-model:api="api"/>
        <el-button @click="handle">Get Rule</el-button>
    </div>
</template>
<script setup>
    import {ref} from 'vue';
    const api = ref(null);
    function handle() {
        const rule = api.value.getRule('field');
        api.value.getRule('name'); //Get rule by name
    }
</script>

Modify Component Rule

vue
<template>
    <div>
        <form-create :v-model:api="api"/>
        <el-button @click="handle">Modify Rule</el-button>
    </div>
</template>
<script setup>
    import {ref} from 'vue';
    const api = ref(null);
    function handle() {
        api.value.getRule('field').prpos.disabled = true;
    }
</script>

Form Validation

vue
<template>
    <div>
        <form-create :v-model:api="api"/>
        <el-button @click="handle">Validate</el-button>
    </div>
</template>
<script setup>
    import {ref} from 'vue';
    const api = ref(null);
    function handle() {
        api.value.validate().then(()=>{
            //todo Validation passed
        });
    }
</script>

Submit Form

vue
<template>
    <div>
        <form-create :v-model:api="api"/>
        <el-button @click="handle">Submit</el-button>
    </div>
</template>
<script setup>
    import {ref} from 'vue';
    const api = ref(null);
    function handle() {
        api.value.submit();
    }
</script>

FormCreate is an open-source project released under the MIT License. Free for personal and commercial use.