API
FormCreate provides rich API interfaces that give developers comprehensive control at various stages of forms, including form generation, dynamic updates, validation, and data processing. These APIs help you easily implement various complex form requirements.
Get API
FormCreate provides multiple ways to obtain the api object, allowing developers to operate and manage forms in different scenarios.
- Global Method
Generate a form and obtain the api object using the create method. This method is suitable 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="fApi"></form-create>Example: Use fApi in Vue components for dynamic form operations:
<template>
<form-create name="form" :rule="rules" v-model:api="fApi"></form-create>
</template>
<script>
export default {
data() {
return {
rules: [
{ type: 'input', field: 'username', title: 'Username', props: { placeholder: 'Enter username' } },
{ type: 'input', field: 'email', title: 'Email', props: { placeholder: 'Enter email' } },
{ type: 'input', field: 'password', title: 'Password', props: { type: 'password', placeholder: 'Enter password' } },
],
fApi: null,
};
},
mounted() {
// Use fApi for operations
this.fApi.setValue('username', 'example_user');
},
};
</script>You can also use the getApi method to obtain the fApi object anywhere, for example, in other components:
const fApi = formCreate.getApi('form')- Event Injection
In form event handler functions, the fApi object can be automatically injected via event parameters. This method is particularly suitable 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: Get fApi object in form component's blur event and perform operations:
const rule = {
type: 'input',
field: 'inputField',
title: 'Input Box',
inject: true,
on: {
blur(inject) {
console.log(inject.api); // Get API object
inject.api.setValue('inputField', 'blurred');
}
}
}- Custom Component Injection
If you use custom components, FormCreate automatically injects some key parameters to help you operate the form within the component.
- 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.
const customComponent = defineComponent({
name: 'custom-component',
props: {
formCreateInject: Object, // Automatically injected form parameters
},
mounted() {
console.log(this.formCreateInject.api); // Access API within component
}
});Data Structure
The following is the complete data structure of the Api and a brief explanation of its available methods:
interface Api {
// Global configuration object of the form, containing all form configuration information
readonly config: Options;
readonly options: Options;
// Current form data object, containing values of all fields
readonly form: Object;
// Current form generation rules list, defining the structure and components of the form
readonly rule: Rule[];
// Parent form's Api object (if the form is a nested sub-form)
readonly parent: Api | undefined;
// Top-level form's Api object (applicable to nested form scenarios)
readonly top: Api | undefined;
// Array of sub-form Api objects, allowing operations on nested sub-forms
readonly children: Api[];
// Submit button control interface, allowing dynamic setting of submit button state
btn: {
// Set submit button loading state, such as loading state
loading(loading: boolean): void;
// Set submit button disabled state
disabled(disabled: boolean): void;
// Set submit button display state, control whether button is visible
show(show: boolean): void;
}
// Reset button control interface, allowing dynamic setting of reset button state
resetBtn: {
// Set reset button loading state
loading(loading: boolean): void;
// Set reset button disabled state
disabled(disabled: boolean): void;
// Set reset button display state
show(show: boolean): void;
}
// Get DOM element or Vue instance of specified component
el(id: string): any;
// Get Vue component instance of the entire form, convenient for directly operating component's internal methods or properties
formEl(): undefined | ComponentInternalInstance;
// Get Vue component instance of specified form item, used for operations on specific form items
wrapEl(id: string): undefined | ComponentInternalInstance;
// Update form submit button configuration, such as text, style, etc.
submitBtnProps(props: ButtonProps): void;
// Update form reset button configuration
resetBtnProps(props: ButtonProps): void;
// Get current form data object, returns values of all fields
formData(): Object;
// Get data of specific fields, returns values of specified fields
formData(field: string[]): Object;
// Get value of specified field
getValue(field: string): any;
// Overwrite current form values with new data
coverValue(formData: Object): void;
// Set form values, can set for entire form or specific fields
setValue(formData: Object): void;
setValue(field: string, value: any): void;
// Delete corresponding component by field name
removeField(field: string): Rule;
// Delete 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 components of the form (no DOM node)
hidden(hidden: Boolean): void;
hidden(hidden: Boolean, field: string | Array<string>): void;
// Control display of form components (with DOM node)
display(hidden: Boolean): void;
display(hidden: Boolean, field: string | Array<string>): void;
// Get hidden state of component, returns boolean
hiddenStatus(field: String): Boolean;
// Get display state of component, returns boolean
displayStatus(field: String): Boolean;
// Disable or enable specified components 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 rules of all components 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 rules list
reload(rules: Rule[]): void;
// Update form's global configuration
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 callbacks
submit(success?: (formData: Object, api: Api) => void, fail?: (api: Api) => void): Promise<any>;
// Sync specified fields or rules, 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 doesn't need to be displayed
hideForm(hide?: Boolean): void;
// Get form's modification state, returns boolean
changeStatus(): Boolean;
// Reset form's modification state
clearChangeStatus(): void;
// Set custom attributes for extending form functionality
setEffect(id: string, attr: string, value: any): void;
// Clear custom attribute data
clearEffectData(id: string, attr?: string): void;
// Update form generation rules of specified field
updateRule(field: string, rule: Rule): void;
updateRule(rules: { [field: string]: Rule }): void;
// Merge form generation rules of specified field
mergeRule(field: string, rule: Rule): void;
mergeRules(rules: { [field: string]: Rule }): void;
// Get generation rules of specified field
getRule(id: string): Rule;
getRule(id: string, origin: true): Rule;
getRule(id: string, origin: false): Rule;
// Get component's final rendering rules, including content after dynamic changes
getRenderRule(id: string): Rule;
// Get component rules through `name` attribute, supports single or multiple components
getRefRule(id: string): Rule | Rule[];
// Update component's validation rules, supports merge or replace
updateValidate(id: string, validate: Object[], merge?: Boolean): Promise<any>;
updateValidates(validates: { [id: string]: Object[] }, merge?: Boolean): Promise<any>;
// Refresh form's validation state, re-trigger validation logic
refreshValidate(): void;
// Clear validation state of specified fields or entire form
clearValidateState(fields?: string | string[], clearSub?: Boolean): void;
// Clear validation state of sub-forms of specified fields
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 to call component's custom methods
method(id: string, name: string): (...args: any[]) => any;
// Manually execute method of specified component
exec(id: string, name: string, ...args: any[]): any;
// Manually trigger component event, suitable for simulating user operations or triggering custom logic
trigger(id: string, event: string, ...args: any[]): void;
// Get form's JSON generation rules, 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 all field values 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 handling
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;
// Refresh components related to external data, ensure UI syncs after data changes
refreshData(id: string): void;
// Built-in event management system, supports manual triggering and listening to form 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 form's custom event
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 form custom event listener
off(event?: string | string[], callback?: Function): this;
}Properties
Form Generation Rules
The rule property represents the current form's generation rules list, defining the structure and configuration of all components in the form. By operating on rule, you can dynamically adjust the form's layout and content.
type rule = Rule[]- Usage:
// Get current form's generation rules
const rules = fApi.rule;
// Modify a component's title
rules[0].title = 'New Title';Form Global Configuration
config is the current form's global configuration object, containing all basic settings of the form, such as button configuration, layout options, etc. fApi.options is an alias for config.
type config = Object- Usage:
// Get current form's global configuration
const options = fApi.config;
// Update form configuration
fApi.updateOptions({ submitBtn: false });Form Data
The form property is the current form's data object, containing values of all fields in the form. This property is two-way bound, meaning you can directly update form data by operating on the form object, and changes in form data will also be reflected synchronously on the form object.
type form = { [field:string]:any }- Usage:
// Get form data
const formData = fApi.form;
// Modify a field's value in the form
formData.goods_name = 'huawei';
// Get form data when submitting form
fApi.onSubmit((formData) => {
console.log('Submitted form data:', formData);
});This property is two-way bound
Parent Form API
The parent property is used to get the current form's parent form API object, applicable to nested form scenarios. When a form is nested within another form, you can access the parent form's API through the parent property.
type parent = Api | undefined;- Usage:
// Get parent form's API object
const parentFormApi = fApi.parent;
// Use parent form's API to operate parent form
if (parentFormApi) {
parentFormApi.submit(); // Submit parent form
}Top-Level Form API
The top property is used to get the current form's top-level form API object. In nested form structures, top always points to the outermost form API.
type top = Api | undefined;- Usage:
// Get top-level form's API object
const topFormApi = fApi.top;
// Reload top-level form's rules
if (topFormApi) {
topFormApi.submit(); // Submit parent form
}Sub-Form API
The children property is used to get a list of all sub-form API objects under the current form. This is very useful for operating multiple sub-forms nested within the current form.
type children = Api[];- Usage:
// Get all sub-form API objects
const subFormApis = fApi.children;
// Iterate through all sub-forms and validate them
subFormApis.forEach(subApi => {
subApi.validate();
});Field Operations
Get Form Fields
The fields method returns a list of names of all fields in the form. This method is very suitable for use when you need to iterate through form fields or dynamically operate on multiple fields.
type fields = ()=>string[]- Usage:
const fields = fApi.fields();
console.log(fields); // Output array of names of all fields in the formGet Specified Field Value
The getValue method gets the current value of the corresponding field based on the field name.
type getValue = (field:string) => any- Usage:
const value = fApi.getValue('goods_name');
console.log(value); // Output current value of specified fieldSet Form Values
The coverValue method will overwrite undefined fields, setting them to undefined.
type coverValue = (formData:{[field:string]:any}) => void- Usage:
fApi.coverValue({ goods_name: 'HuaWei', price: 1000 });
// Overwrite all fields, undefined fields will be set to undefinedThe setValue method will merge the passed field values, fields not defined in formData will not be modified.
interface setValue {
(formData:{[field:string]:any}): void
(field:string, value:any): void
}- Usage:
fApi.setValue({ goods_name: 'HuaWei', price: 1000 });
// Or set a single field's value
fApi.setValue('goods_name', 'HuaWei');Alias methods changeValue, changeField
Reset Form Values
The resetFields method is used to reset all field values of the form, or reset values of specified fields.
interface resetFields {
():void
(field:string[]):void
}- Usage:
fApi.resetFields(); // Reset values of all fields
fApi.resetFields(['goods_name', 'price']); // Only reset values of specified fieldsHide Fields (No Rendering)
Hidden field components will not be rendered, DOM nodes will not be generated, so form validation will not take effect.
interface hidden {
//Hide all components
(status:Boolean):void
//Hide specified component
(status:Boolean, field:string):void
//Hide some components
(status:Boolean, field:string[]):void
}- Usage:
fApi.hidden(true); // Hide all components
fApi.hidden(true, 'goods_name'); // Hide specified component
fApi.hidden(true, ['goods_name', 'price']); // Hide multiple componentsGet Component Hidden Status
The hiddenStatus method is used to get whether a specified field is in hidden state.
type hiddenStatus = (field:string)=>Boolean- Usage:
const status = fApi.hiddenStatus('goods_name');
console.log(status); // Output true or falseHide Components (Rendered)
Hide components through display: none, components are still rendered but not displayed.
interface display {
//Hide all components
(status:Boolean):void
//Hide specified component
(status:Boolean, field:string):void
//Hide some components
(status:Boolean, field:string[]):void
}- Usage:
fApi.display(false); // Show all components
fApi.display(false, 'goods_name'); // Show specified component
fApi.display(false, ['goods_name', 'price']); // Show multiple componentsGet Component Display Status
The displayStatus method is used to get whether a specified field is in display state.
type displayStatus = (field:string)=>Boolean- Usage:
const status = fApi.displayStatus('goods_name');
console.log(status); // Output true or falseDisable Components
The disabled method is used to disable all components, specified components, or some components in the form.
interface disabled {
//Disable all components
(status:Boolean):void
//Disable specified component
(status:Boolean, field:string):void
//Disable some components
(status:Boolean, field:string[]):void
}- Usage:
fApi.disabled(true); // Disable all components
fApi.disabled(true, 'goods_name'); // Disable specified component
fApi.disabled(true, ['goods_name', 'price']); // Disable multiple componentsDelete Field
The removeField method is used to delete a specified component from the form.
type removeField = (field:string) => Rule- Usage:
const rule = fApi.removeField('goods_name');
console.log(rule); // Return deleted field's generation ruleRefresh Component Rendering
The sync method is used to manually refresh component rendering of specified fields.
interface sync{
//Update specified component through field
(field:string):void
//Update specified component through generation rule
(rule:Rule):void
}- Usage:
fApi.sync('goods_name'); // Refresh component of specified field
fApi.sync(rule); // Refresh component through generation ruleComponent Methods
The exec method is used to manually execute a method of a specified field component.
type exec = (field:string, method:string, ...args:any[]) => any- Usage:
fApi.exec('goods_name', 'focus'); // Make component of specified field gain focusThe method method is used to get a method of a specified field component for subsequent manual calls.
type method = (field:string, method:string) => Function- Usage:
const focusMethod = fApi.method('goods_name', 'focus');
focusMethod(); // Manually call component's focus methodManually Trigger Component Events
The trigger method is used to manually trigger events of specified field components.
type trigger = (field:string, event:string, ...args:any[]) => void- Usage:
fApi.trigger('goods_name', 'change', 'new value'); // Manually trigger change eventGet Component's vm/dom Element
The el method is used to get the Vue instance or DOM element of a specified field component.
type el = (field:string) => Vue|Document|undefined- Usage:
const vm = fApi.el('goods_name');
console.log(vm); // Output component's Vue instance or DOM elementClose Frame Component's Popup
The closeModal method is used to close the popup of a specified frame component.
type closeModal = (field:string) => void- Usage:
fApi.closeModal('frame'); // Close popup of specified frame componentRule Operations
Get Component Rules
Get Rules of Specified Field
The getRule method is used to get rules of a specified field. You can choose to get the original rule or the current rule state.
interface getRule {
(field:string):Rule
(field:string, origin: true): Rule
}- Usage:
const rule = fApi.getRule('goods_name');
console.log(rule); // Get generation rule of current fieldGet Component Rules Through name
The getRefRule method gets component generation rules through name. Suitable for scenarios where multiple components use the same name.
interface getRefRule {
(name:string):Rule | Rule[]
}- Usage:
const rule = fApi.getRefRule('input');
console.log(rule); // Get rule corresponding to specified nameGet Component's Final Rendering Rules The getRenderRule method gets the component's final rendering rules, i.e., the rule configuration in the component's current state.
interface getRenderRule {
(field:string):Rule
}- Usage:
const rule = fApi.getRenderRule('input');
console.log(rule); // Get final rendering rulesInsert Components
The prepend method is used to prepend new rules in form rules, can insert to the first position, before specified field, or as a child rule.
interface prepend {
//Insert to first
(rule:Rule):void
//Insert before specified field
(rule:Rule, field:string):void
//Insert into specified field's children
(rule:Rule, field:string, child:true):void
}- Usage:
fApi.prepend({
type: "input",
title: "Product Introduction",
field: "goods_info",
value: "",
props: {
type: "text",
placeholder: "Enter product introduction",
},
validate: [
{ required: true, message: 'Enter product introduction', trigger: 'blur' },
],
}, 'goods_name'); // Insert new rule before 'goods_name'The append method is used to append new rules in form rules, can insert to the last position, after specified field, or as a child rule.
interface append {
//Insert to last
(rule:Rule):void
//Insert after specified field
(rule:Rule, field:string):void
//Insert into specified field's children
(rule:Rule, field:string, child:true):void
}- Usage:
fApi.append({
type: "input",
title: "Product Introduction",
field: "goods_info",
value: "",
props: {
type: "text",
placeholder: "Enter product introduction",
},
validate: [
{ required: true, message: 'Enter product introduction', trigger: 'blur' },
],
}, 'goods_name'); // Insert new rule after 'goods_name'Delete Specified Component
The removeRule method is used to delete a component with specified rule from the form, and returns the deleted rule.
type removeRule = (rule:Rule) => Rule- Usage:
const rule = { type: 'input', field: 'goods_info' };
fApi.removeRule(rule);
console.log('Rule deleted:', rule);Get Form Component Rules
The model method is used to get all generation rules or original rules of the current form.
interface model{
//Get Object rules
():Rule[]
//Get original rules
(origin:true):Rule[]
}- Usage:
const rules = fApi.model(); // Get rules in current state
console.log(rules);
const originalRules = fApi.model(true); // Get original rules
console.log(originalRules);Get Custom Component Rules
The component method is used to get rules of all custom components with name attribute defined.
interface component{
//Get Object rules
():Rule[]
//Get original rules
(origin:true):Rule[]
}- Usage:
const componentRules = fApi.component(); // Get custom component rules in current state
console.log(componentRules);Update Specified Rules
The mergeRule method is used to merge and update rules of specified field.
type mergeRule = (rule:Rule)=>void- Usage:
fApi.mergeRule('goods_name', { hidden: true }); // Merge and update rules of 'goods_name' fieldThe mergeRules method is used to batch merge and update rules of multiple fields.
type mergeRules = (rules:{[field:string]:Rule})=>void- Usage:
fApi.mergeRules({ 'goods_name': { hidden: true }, 'price': { disabled: true } });The updateRule method is used to overwrite and update rules of specified field.
type updateRule = (rule:Rule)=>void- Usage:
fApi.updateRule('goods_name', { props: {disabled: true} }); // Overwrite and update rules of 'goods_name' fieldThe updateRules method is used to batch overwrite and update rules of multiple fields.
type updateRules = (rules:{[field:string]:Rule})=>void- Usage:
fApi.updateRules({ 'goods_name': { props: {disabled: true} }, 'price': { props: {disabled: true} } });Update Custom Attributes
The setEffect method is used to update custom attributes of specified field.
type setEffect = (id:string, attr: string, value:any)=>void- Usage:
fApi.setEffect('goods_name', 'required', false); // Set 'required' attribute of 'goods_name' field to falseValidation Operations
Validate Form
The validate method is used to validate the entire form and return validation results in the callback. This method returns a Promise object, resolves if validation passes, otherwise rejects.
type validate = (callback:(...args:any[]) => void)=> Promise- Usage:
fApi.validate((valid, fail) => {
if (valid === true) {
console.log('Form validation passed');
} else {
console.log('Form validation failed');
}
}).then(() => {
//Recommended
console.log('Promise resolved: Form validation passed');
}).catch(() => {
console.log('Promise rejected: Form validation failed');
});Validate Specified Field
The validateField method is used to validate a specified field and return validation results in the callback. This method returns a Promise object, resolves if validation passes, otherwise rejects.
type validateField = (field, callback:(...args:any[]) => void)=> Promise- Usage:
fApi.validateField('goods_name', (valid, fail) => {
if (valid === true) {
console.log('Field validation passed');
// todo Handle logic after field validation passes
} else {
console.log('Field validation failed');
// todo Handle logic after field validation fails
}
}).then(() => {
//Recommended
console.log('Promise resolved: Field validation passed');
}).catch(() => {
console.log('Promise rejected: Field validation failed');
});Update Validation Rules
The updateValidate method is used to update validation rules of a specified field. You can choose to overwrite or merge update.
interface updateValidate{
//Overwrite update
(field:string, validate:Object[]):void
//Merge update
(field:string, validate:Object[], merge:true):void
}- Usage:
// Merge update validation rules of goods_name field
fApi.updateValidate('goods_name', [{ required: true }], true);
// Overwrite update validation rules of goods_name field
fApi.updateValidate('goods_name', [{ required: true }]);The updateValidates method is used to batch update validation rules of multiple fields. You can choose to overwrite or merge update.
interface updateValidates{
//Overwrite update
(validates:{[field:string]: Object[]}):void
//Merge update
(validates:{[field:string]: Object[]}, merge:true):void
}- Usage:
// Merge update validation rules of multiple fields
fApi.updateValidates({
'goods_name': [{ required: false }],
'price': [{ required: true, type: 'number' }]
}, true);
// Overwrite update validation rules of multiple fields
fApi.updateValidates({
'goods_name': [{ required: true }],
'price': [{ required: true, type: 'number' }]
});Refresh Validation Rules
The refreshValidate method is used to manually refresh form validation rules. If validation rules are modified but not effective, you can call this method to ensure rules take effect.
type refreshValidate = ()=>void- Usage:
fApi.refreshValidate();
console.log('Validation rules refreshed');Clear Form Validation State
The clearValidateState method is used to clear validation state of the form or specified fields.
interface clearValidateState {
():void
(field:string, clearSub?:boolean):void
(field:string[], clearSub?:boolean):void
}- Usage:
// Clear validation state of entire form
fApi.clearValidateState();
// Clear validation state of single field
fApi.clearValidateState('goods_name');
// Clear validation state of multiple fields
fApi.clearValidateState(['goods_name', 'price']);Clear Sub-Form Validation State
The clearSubValidateState method is used to clear validation state of sub-forms such as group, object, etc.
interface clearSubValidateState {
(field:string):void
(field:string[]):void
}- Usage:
// Clear validation state of single sub-form
fApi.clearSubValidateState('goods_name');
// Clear validation state of multiple sub-forms
fApi.clearSubValidateState(['goods_name', 'price']);Form Operations
Get Form Component's vm/dom Element
The formEl method is used to get the Vue instance or DOM element of the entire form component.
type formEl = () => Vue|Document|undefined- Usage:
const vm = fApi.formEl();
console.log(vm);Get FormItem Component's vm/dom Element
The wrapEl method is used to get the Vue instance or DOM element of the FormItem component of a specified field.
type wrapEl = (field:string) => Vue|Document|undefined- Usage:
const vm = fApi.wrapEl('goods_name');
console.log(vm);Get Form Data
The formData method is used to get data of all fields or some fields in the form. The return value of this method is a snapshot of data, not two-way bound.
interface formData {
//Get all data
(): {[field:string]:any }
//Get data of some fields
(field:string[]): {[field:string]:any }
}- Usage:
const allData = fApi.formData();
console.log('All form data:', allData);
const specificData = fApi.formData(['goods_name', 'price']);
console.log('Partial form data:', specificData);Whether Form Values Have Changed
The changeStatus method is used to check whether values in the form have changed. The returned boolean indicates whether the form has been modified by the user since loading.
type changeStatus = ()=>Boolean- Usage:
const hasChanged = fApi.changeStatus();
if (hasChanged) {
console.log('Form data has been modified');
} else {
console.log('Form data has not been modified');
}Clear Change Status
The clearChangeStatus method is used to clear the form's change status, meaning that after calling this method, changeStatus will return false.
type clearChangeStatus = ()=>void- Usage:
fApi.clearChangeStatus();
console.log('Form change status cleared');Modify Submit Button
The submitBtnProps method is used to dynamically modify properties of the form submit button, such as disabled state, loading state, or button text.
type submitBtnProps = (props:Object) => void- Usage:
fApi.submitBtnProps({ disabled: true });Shortcut Operations:
fApi.btn.loading(true)Set submit button to loading statefApi.btn.disabled(true)Set submit button to disabled statefApi.btn.show(true)Set submit button to show state
Modify Reset Button
The resetBtnProps method is used to dynamically modify properties of the form reset button, such as disabled state, loading state, or button text.
type resetBtnProps = ( props:Object) => void- Usage:
fApi.resetBtnProps({ disabled: true });Shortcut Operations:
fApi.resetBtn.loading(true)Set reset button to loading statefApi.resetBtn.disabled(true)Set reset button to disabled statefApi.resetBtn.show(true)Set reset button to show state
Update Form Configuration
The updateOptions method is used to dynamically update global configuration options of the form. These configuration options include form layout, button configuration, validation rules, etc.
type updateOptions = (options:Object) => void- Usage:
fApi.updateOptions({ form: { inline: true } });Update Form Submit Event
The onSubmit method is used to set a custom submit event handler function for the form. When the user submits the form, this callback function will be executed, and you can process form data in the callback.
type onSubmit = (callback:(formData:Object,fApi:fApi)=>void) => void- Usage:
fApi.onSubmit((formData, fApi) => {
console.log('Form submit data:', formData);
// Custom submit logic
});Refresh Form Configuration
The refreshOptions method is used to manually refresh form configuration options, ensuring configuration changes take effect immediately.
type refreshOptions = ()=>void- Usage:
fApi.refreshOptions();
console.log('Form configuration refreshed');Refresh Form Rendering
The refresh method is used to manually refresh the form's rendering state. This is very useful when form content needs to be dynamically updated.
type refresh = ()=>void- Usage:
fApi.refresh();
console.log('Form rendering refreshed');Hide Form
The hideForm method is used to hide or show the entire form. After the form is hidden, users will not be able to see or operate the form.
type hideForm = (hide:Boolean)=>void- Usage:
fApi.hideForm(true); // Hide form
fApi.hideForm(false); // Show formReload Form
The reload method is used to reload the form. You can choose to use existing generation rules or pass new generation rules to reload the form.
interface reload{
():void
(rules:Rule[]):void
}- Usage:
fApi.reload(); // Reload form with existing rules
fApi.reload(newRules); // Reload form with new rulesCallback After Form Rendering
The nextTick method executes a callback function after form rendering is complete. Can be used to ensure DOM operations are performed after rendering is complete.
type nextTick = (callback:Function) => void- Usage:
fApi.nextTick(() => {
console.log('Form rendering completed');
// Operations after rendering is complete
});Auto Refresh
The nextRefresh method automatically refreshes form rendering after executing the callback function. This is particularly useful when executing operations that affect form rendering in the callback.
type nextRefresh = (callback:Function) => void- Usage:
fApi.nextRefresh(() => {
console.log('Form operation completed, refreshing form...');
// Execute operations that affect form rendering
});Submit Form
The submit method is used to manually submit the form, supports passing success and failure callback functions. Custom validation and data processing can be performed when submitting the form.
type submit = (
success?: (formData: Object, $f: Api) => void,
fail?: ($f: Api) => void
) => Promise<any>;- Usage:
fApi.submit(
(formData, fApi) => {
console.log('Form submitted successfully:', formData);
// Logic handling after submission
},
(fApi) => {
console.log('Form submission failed');
// Logic handling when validation fails
}
).then(formData => {
// Recommended
console.log('Form submitted successfully:', formData);
// Logic handling after submission
});Get Form json Rules
The toJson method is used to convert form rules to JSON string.
type toJson = () => string- Usage:
const jsonString = fApi.toJson();
console.log('JSON string of form rules:', jsonString);Data Management
Remote Request
The fetch method is used to initiate remote requests to get external data or send data to the server. It is deeply integrated with form components and can dynamically update form options or data based on request results.
type fetch = (opt: FetchOption) => Promise<any>;fApi.fetch({
action: '/api/get-options',
method: 'GET',
to: 'props.options',
onSuccess(data) {
console.log('Data retrieved:', data);
},
onError(error) {
console.error('Request failed:', error);
}
});Set External Data
The setData method is used to mount external data into the form, making this data available for use by components in the form. This data can be static or dynamically obtained from external data sources.
type setData = (id: string, value?: any)=> void;fApi.setData('categories', [
{ label: 'Electronics', value: 'electronics' },
{ label: 'Clothing', value: 'clothing' },
{ label: 'Home & Garden', value: 'home_garden' },
]);
console.log('External data set:', fApi.getData('categories'));Get External Data
The getData method is used to get external data previously set through the setData method. If the specified data is not set, the method will return defaultValue.
type getData = (id: string, defaultValue?: any) => any;const categories = fApi.getData('categories', []);
console.log('Category data retrieved:', categories);Refresh Component Rendering Related to External Data
The refreshData method is used to manually refresh component rendering related to specified external data. When external data changes, you can call this method to ensure form components correctly reflect the latest data state.
type refreshData = (id: string) => void;fApi.setData('categories', [
{ label: 'Books', value: 'books' },
{ label: 'Music', value: 'music' },
]);
fApi.refreshData('categories');
console.log('Components related to category data refreshed');Built-in Event Management
Trigger Event
The bus.$emit method is used to manually trigger a specified event and can pass multiple parameters. These parameters will be passed as arguments to the event handler function.
type emit = (event:string, ...args:any[]) => void- Usage:
fApi.bus.$emit('custom-event', 'param1', 'param2');Listen to Event
The bus.$on method is used to listen to specified events. When an event is triggered, the registered callback function will be executed. Can listen to one or multiple events.
type on = (event: string, callback: Function) => void- Usage:
fApi.bus.$on('custom-event', (param1, param2) => {
console.log('Event triggered:', param1, param2);
});Listen to Event, Trigger Only Once
The bus.$once method is used to listen to a specified event, but the callback function will only execute once, and will automatically cancel listening after execution.
type on = (event: string, callback: Function) => void- Usage:
fApi.bus.$once('init-complete', () => {
console.log('Initialization complete, event triggered only once');
});Cancel Event Listener
The bus.$off method is used to cancel listening to specified events.
type off = (event: string, callback: Function) => void- Usage:
fApi.bus.$off('custom-event', handleCustomEvent);

