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.
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.
<form-create name="form" :rule="rules" v-model:api="api"></form-create>Example: Using the API in a Vue component for dynamic form operations:
<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:
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.
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:
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
formCreateInjectobject contains the following properties:formCreateInject.apiForm API object for operating the form.formCreateInject.optionsGlobal configuration of the form component.formCreateInject.ruleGeneration rule object that defines all configurations of the component.formCreateInject.fieldField name bound to form data.
Example: Using the formCreateInject object in a custom component for operations:
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 Name | Type | Description |
|---|---|---|
| config | Options | Global configuration object of the form |
| index | number|undefined | Index of the current form in the sub-form |
| siblings | Api[]|undefined | API array of sibling forms |
| rule | Rule[] | Generation rule list of the current form |
| form | Object | Data object of the current form |
| parent | Api|undefined | API object of the parent form |
| top | Api|undefined | API object of the top-level form |
| children | Api[] | API object array of sub-forms |
Api Methods
Button Control Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| btn.loading | loading: boolean | void | Set submit button loading state |
| btn.disabled | disabled: boolean | void | Set submit button disabled state |
| btn.show | show: boolean | void | Set submit button display state |
| resetBtn.loading | loading: boolean | void | Set reset button loading state |
| resetBtn.disabled | disabled: boolean | void | Set reset button disabled state |
| resetBtn.show | show: boolean | void | Set reset button display state |
| submitBtnProps | props: ButtonProps | void | Update submit button configuration |
| resetBtnProps | props: ButtonProps | void | Update reset button configuration |
Element Operation Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| el | id: string | any | Get DOM element or Vue instance of the specified component |
| formEl | - | ComponentInternalInstance|undefined | Get Vue component instance of the entire form |
| wrapEl | id: string | ComponentInternalInstance|undefined | Get Vue component instance of the specified form item |
Data Operation Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| formData | - | Object | Get current form data object |
| formData | field: string[] | Object | Get data of specific fields |
| getValue | field: string | any | Get value of the specified field |
| coverValue | formData: Object | void | Overwrite current form values with new data |
| setValue | formData: Object | void | Set values for the entire form |
| setValue | field: string, value: any | void | Set value of a specific field |
Form Structure Operation Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| removeField | field: string | Rule | Remove component by field name |
| removeRule | rule: Rule | Rule | Remove component by rule |
| fields | - | string[] | Get all field names |
| append | rule: Rule | void | Append new component |
| append | rule: Rule, field: string | void | Append component after specified field |
| append | rule: Rule, field: string, child: boolean | void | Append child component after specified field |
| prepend | rule: Rule | void | Insert new component at the beginning |
| prepend | rule: Rule, field: string | void | Insert component before specified field |
| prepend | rule: Rule, field: string, child: boolean | void | Insert child component before specified field |
Display Control Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| hidden | hidden: Boolean | void | Hide/show form component (no DOM) |
| hidden | hidden: Boolean, field: string|Array<string> | void | Hide/show specified component |
| display | hidden: Boolean | void | Control component display (with DOM) |
| display | hidden: Boolean, field: string|Array<string> | void | Control specified component display |
| hiddenStatus | field: String | Boolean | Get component hidden state |
| displayStatus | field: String | Boolean | Get component display state |
| disabled | disabled: Boolean | void | Disable/enable form component |
| disabled | disabled: Boolean, field: string|Array<string> | void | Disable/enable specified component |
Rule Operation Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| model | - | { [field: string]: Rule } | Get form component generation rules |
| component | - | { [name: string]: Rule } | Get all component rules with name attribute defined |
| reload | rules: Rule[] | void | Reload form rules |
| updateOptions | options: Options | void | Update form global configuration |
| updateRule | field: string, rule: Rule | void | Update specified field rule |
| updateRule | rules: { [field: string]: Rule } | void | Batch update field rules |
| mergeRule | field: string, rule: Rule | void | Merge specified field rule |
| mergeRules | rules: { [field: string]: Rule } | void | Batch merge field rules |
| getRule | id: string | Rule | Get specified field rule |
| getRule | id: string, origin: true | Rule | Get original rule |
| getRule | id: string, origin: false | Rule | Get processed rule |
| findType | type: string | Rule | Get rule by component type |
| findTypes | type: string | Rule[] | Get multiple rules by component type |
| getCurrentFormRule | - | Rule | Get current sub-form rule |
| getRenderRule | id: string | Rule | Get component final rendering rule |
| getRefRule | id: string | Rule|Rule[] | Get rule by name attribute |
| getParentRule | id: string|Rule | Rule|undefined | Get parent rule |
Validation Related Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| updateValidate | id: string, validate: Object[], merge?: Boolean | Promise<any> | Update component validation rules |
| updateValidates | validates: { [id: string]: Object[] }, merge?: Boolean | Promise<any> | Batch update validation rules |
| refreshValidate | - | void | Refresh form validation state |
| clearValidateState | fields?: string|string[], clearSub?: Boolean | void | Clear validation state |
| clearSubValidateState | fields?: string|string[] | void | Clear sub-form validation state |
| validate | callback?: (state: any) => void | Promise<any> | Validate entire form |
| validateField | field: string, callback?: (state: any) => void | Promise<any> | Validate specified field |
Component Operation Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| method | id: string, name: string | (...args: any[]) => any | Get component method |
| exec | id: string, name: string, ...args: any[] | any | Execute component method |
| trigger | id: string, event: string, ...args: any[] | void | Trigger component event |
Form Operation Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| onSubmit | fn: (formData: Object, api: Api) => void | void | Listen to form submit event |
| submit | success?: (formData: Object, api: Api) => void, fail?: (api: Api) => void | Promise<any> | Manually submit form |
| sync | field: string|string[] | void | Sync specified field |
| sync | rule: Rule|Rule[] | void | Sync specified rule |
| refresh | - | void | Re-render entire form |
| refreshOptions | - | void | Refresh form options |
| hideForm | hide?: Boolean | void | Hide entire form |
| changeStatus | - | Boolean | Get form modification state |
| clearChangeStatus | - | void | Reset form modification state |
| toJson | space?: string|number | string | Get form JSON rules |
| closeModal | id: string | void | Close frame component popup |
| resetFields | - | void | Reset entire form |
| resetFields | field: string|string[] | void | Reset specified field |
| getSubForm | field: string | Api|Api[] | Get sub-form API object |
Async Operation Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| nextTick | fn: (api: Api) => void | void | Execute callback after form rendering |
| nextRefresh | fn: Function | void | Re-render form after callback |
| deferSyncValue | fn: Function, autoSync?: boolean | void | Sync form data after callback |
Data Management Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| fetch | opt: FetchOption | Promise<any> | Send remote request |
| setData | id: string, value?: any | void | Set external data |
| getData | id: string, defaultValue?: any | any | Get external data |
| watchData | fn: (get: (id: string, defaultValue?: any) => any, change: boolean) => void | () => Function | Watch data changes |
| refreshData | id: string | void | Refresh components related to external data |
Event Management Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| bus.$emit | event: string, ...args: any[] | void | Manually trigger event |
| bus.$on | event: string|string[], callback: Function | void | Listen to event |
| bus.$once | event: string|string[], callback: Function | void | Listen to one-time event |
| bus.$off | event: string|string[], callback: Function | void | Cancel event listener |
| emit | event: string, ...args: any[] | void | Trigger form custom event |
| on | event: string|string[], callback: Function | this | Listen to form custom event |
| once | event: string|string[], callback: Function | this | Listen to one-time form event |
| off | event?: string|string[], callback?: Function | this | Cancel form event listener |
Custom Property Methods
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| setEffect | id: string, attr: string, value: any | void | Set custom property |
| clearEffectData | id: string, attr?: string | void | Clear custom property data |
Data Structure
The following is a concise explanation of the complete data structure of the Api and its available methods:
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
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
<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
<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
<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
<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
<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
<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>

