Skip to content

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.

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="fApi"></form-create>

Example: Use fApi in Vue components for dynamic form operations:

vue
<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:

js
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.

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: Get fApi object in form component's blur event and perform operations:

js
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 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.
js
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:

ts
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.

typescript
type rule = Rule[]
  • Usage:
js
// 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.

typescript
type config = Object
  • Usage:
js
// 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.

typescript
type form = { [field:string]:any }
  • Usage:
js
// 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.

typescript
type parent = Api | undefined;
  • Usage:
js
// 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.

typescript
type top = Api | undefined;
  • Usage:
js
// 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.

typescript
type children = Api[];
  • Usage:
js
// 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.

typescript
type fields = ()=>string[]
  • Usage:
js
const fields = fApi.fields();
console.log(fields); // Output array of names of all fields in the form

Get Specified Field Value

The getValue method gets the current value of the corresponding field based on the field name.

typescript
type getValue = (field:string) => any
  • Usage:
js
const value = fApi.getValue('goods_name');
console.log(value); // Output current value of specified field

Set Form Values

The coverValue method will overwrite undefined fields, setting them to undefined.

typescript
type coverValue = (formData:{[field:string]:any}) => void
  • Usage:
js
fApi.coverValue({ goods_name: 'HuaWei', price: 1000 });
// Overwrite all fields, undefined fields will be set to undefined

The setValue method will merge the passed field values, fields not defined in formData will not be modified.

typescript
interface setValue {
    (formData:{[field:string]:any}): void
    (field:string, value:any): void
}
  • Usage:
js
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.

typescript
interface resetFields {
    ():void
    (field:string[]):void
}
  • Usage:
js
fApi.resetFields(); // Reset values of all fields
fApi.resetFields(['goods_name', 'price']); // Only reset values of specified fields

Hide Fields (No Rendering)

Hidden field components will not be rendered, DOM nodes will not be generated, so form validation will not take effect.

typescript
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:
js
fApi.hidden(true); // Hide all components
fApi.hidden(true, 'goods_name'); // Hide specified component
fApi.hidden(true, ['goods_name', 'price']); // Hide multiple components

Get Component Hidden Status

The hiddenStatus method is used to get whether a specified field is in hidden state.

typescript
type hiddenStatus = (field:string)=>Boolean
  • Usage:
js
const status = fApi.hiddenStatus('goods_name');
console.log(status); // Output true or false

Hide Components (Rendered)

Hide components through display: none, components are still rendered but not displayed.

typescript
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:
js
fApi.display(false); // Show all components
fApi.display(false, 'goods_name'); // Show specified component
fApi.display(false, ['goods_name', 'price']); // Show multiple components

Get Component Display Status

The displayStatus method is used to get whether a specified field is in display state.

typescript
type displayStatus = (field:string)=>Boolean
  • Usage:
js
const status = fApi.displayStatus('goods_name');
console.log(status); // Output true or false

Disable Components

The disabled method is used to disable all components, specified components, or some components in the form.

typescript
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:
js
fApi.disabled(true); // Disable all components
fApi.disabled(true, 'goods_name'); // Disable specified component
fApi.disabled(true, ['goods_name', 'price']); // Disable multiple components

Delete Field

The removeField method is used to delete a specified component from the form.

typescript
type removeField = (field:string) => Rule
  • Usage:
js
const rule = fApi.removeField('goods_name');
console.log(rule); // Return deleted field's generation rule

Refresh Component Rendering

The sync method is used to manually refresh component rendering of specified fields.

typescript
interface sync{
    //Update specified component through field
    (field:string):void
    //Update specified component through generation rule
    (rule:Rule):void
}
  • Usage:
js
fApi.sync('goods_name'); // Refresh component of specified field
fApi.sync(rule); // Refresh component through generation rule

Component Methods

The exec method is used to manually execute a method of a specified field component.

typescript
type exec = (field:string, method:string, ...args:any[]) => any
  • Usage:
js
fApi.exec('goods_name', 'focus'); // Make component of specified field gain focus

The method method is used to get a method of a specified field component for subsequent manual calls.

typescript
type method = (field:string, method:string) => Function
  • Usage:
js
const focusMethod = fApi.method('goods_name', 'focus');
focusMethod(); // Manually call component's focus method

Manually Trigger Component Events

The trigger method is used to manually trigger events of specified field components.

typescript
type trigger = (field:string, event:string, ...args:any[]) => void
  • Usage:
js
fApi.trigger('goods_name', 'change', 'new value'); // Manually trigger change event

Get Component's vm/dom Element

The el method is used to get the Vue instance or DOM element of a specified field component.

typescript
type el = (field:string) => Vue|Document|undefined
  • Usage:
js
const vm = fApi.el('goods_name');
console.log(vm); // Output component's Vue instance or DOM element

Close Frame Component's Popup

The closeModal method is used to close the popup of a specified frame component.

typescript
type closeModal = (field:string) => void
  • Usage:
js
fApi.closeModal('frame'); // Close popup of specified frame component

Rule 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.

typescript
interface getRule {
    (field:string):Rule
    (field:string, origin: true): Rule
}
  • Usage:
js
const rule = fApi.getRule('goods_name');
console.log(rule); // Get generation rule of current field

Get Component Rules Through name

The getRefRule method gets component generation rules through name. Suitable for scenarios where multiple components use the same name.

typescript
interface getRefRule {
    (name:string):Rule | Rule[]
}
  • Usage:
js
const rule = fApi.getRefRule('input');
console.log(rule); // Get rule corresponding to specified name

Get 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.

typescript
interface getRenderRule {
    (field:string):Rule
}
  • Usage:
js
const rule = fApi.getRenderRule('input');
console.log(rule); // Get final rendering rules

Insert 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.

typescript
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:
js
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.

typescript
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:
js
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.

typescript
type removeRule = (rule:Rule) => Rule
  • Usage:
js
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.

typescript
interface model{                
    //Get Object rules
    ():Rule[]              
    //Get original rules
    (origin:true):Rule[]
}
  • Usage:
js
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.

typescript
interface component{                
    //Get Object rules
    ():Rule[]              
    //Get original rules
    (origin:true):Rule[]
}
  • Usage:
js
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.

typescript
type mergeRule = (rule:Rule)=>void
  • Usage:
js
fApi.mergeRule('goods_name', { hidden: true }); // Merge and update rules of 'goods_name' field

The mergeRules method is used to batch merge and update rules of multiple fields.

typescript
type mergeRules = (rules:{[field:string]:Rule})=>void
  • Usage:
js
fApi.mergeRules({ 'goods_name': { hidden: true }, 'price': { disabled: true } });

The updateRule method is used to overwrite and update rules of specified field.

typescript
type updateRule = (rule:Rule)=>void
  • Usage:
js
fApi.updateRule('goods_name', { props: {disabled: true} }); // Overwrite and update rules of 'goods_name' field

The updateRules method is used to batch overwrite and update rules of multiple fields.

typescript
type updateRules = (rules:{[field:string]:Rule})=>void
  • Usage:
js
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.

typescript
type setEffect = (id:string, attr: string, value:any)=>void
  • Usage:
js
fApi.setEffect('goods_name', 'required', false); // Set 'required' attribute of 'goods_name' field to false

Validation 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.

typescript
type validate = (callback:(...args:any[]) => void)=> Promise
  • Usage:
js
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.

typescript
type validateField = (field, callback:(...args:any[]) => void)=> Promise
  • Usage:
js
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.

typescript
interface updateValidate{
    //Overwrite update
    (field:string, validate:Object[]):void
    //Merge update
    (field:string, validate:Object[], merge:true):void
}
  • Usage:
js
// 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.

typescript
interface updateValidates{
    //Overwrite update
    (validates:{[field:string]: Object[]}):void
    //Merge update
    (validates:{[field:string]: Object[]}, merge:true):void
}
  • Usage:
js
// 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.

typescript
type refreshValidate = ()=>void
  • Usage:
js
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.

typescript
interface clearValidateState {
    ():void
    (field:string, clearSub?:boolean):void
    (field:string[], clearSub?:boolean):void
}
  • Usage:
js
// 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.

typescript
interface clearSubValidateState {
    (field:string):void
    (field:string[]):void
}
  • Usage:
js
// 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.

typescript
type formEl = () => Vue|Document|undefined
  • Usage:
js
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.

typescript
type wrapEl = (field:string) => Vue|Document|undefined
  • Usage:
js
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.

typescript
interface formData {
    //Get all data
    (): {[field:string]:any }
    //Get data of some fields
    (field:string[]): {[field:string]:any }
}
  • Usage:
js
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.

typescript
type changeStatus = ()=>Boolean
  • Usage:
js
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.

typescript
type clearChangeStatus = ()=>void
  • Usage:
js
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.

typescript
type submitBtnProps = (props:Object) => void
  • Usage:
js
fApi.submitBtnProps({ disabled: true });
  • Shortcut Operations:

  • fApi.btn.loading(true) Set submit button to loading state

    • fApi.btn.disabled(true) Set submit button to disabled state
    • fApi.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.

typescript
type resetBtnProps = ( props:Object) => void
  • Usage:
js
fApi.resetBtnProps({ disabled: true });
  • Shortcut Operations:

  • fApi.resetBtn.loading(true) Set reset button to loading state

    • fApi.resetBtn.disabled(true) Set reset button to disabled state
    • fApi.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.

typescript
type updateOptions = (options:Object) => void
  • Usage:
js
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.

typescript
type onSubmit = (callback:(formData:Object,fApi:fApi)=>void) => void
  • Usage:
js
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.

typescript
type refreshOptions = ()=>void
  • Usage:
js
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.

typescript
type refresh = ()=>void
  • Usage:
js
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.

typescript
type hideForm = (hide:Boolean)=>void
  • Usage:
js
fApi.hideForm(true); // Hide form
fApi.hideForm(false); // Show form

Reload 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.

typescript
interface reload{
    ():void
    (rules:Rule[]):void
}
  • Usage:
js
fApi.reload(); // Reload form with existing rules
fApi.reload(newRules); // Reload form with new rules

Callback 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.

typescript
type nextTick = (callback:Function) => void
  • Usage:
js
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.

typescript
type nextRefresh = (callback:Function) => void
  • Usage:
js
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.

typescript
type submit = (
    success?: (formData: Object, $f: Api) => void,
    fail?: ($f: Api) => void
) => Promise<any>;
  • Usage:
js
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.

typescript
type toJson = () => string
  • Usage:
js
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.

typescript
type fetch = (opt: FetchOption) => Promise<any>;
js
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.

typescript
type setData = (id: string, value?: any)=> void;
js
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.

typescript
type getData = (id: string, defaultValue?: any) => any;
js
const categories = fApi.getData('categories', []);
console.log('Category data retrieved:', categories);

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.

typescript
type refreshData = (id: string) => void;
js
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.

typescript
type emit = (event:string, ...args:any[]) => void
  • Usage:
js
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.

typescript
type on = (event: string, callback: Function) => void
  • Usage:
js
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.

typescript
type on = (event: string, callback: Function) => void
  • Usage:
js
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.

typescript
type off = (event: string, callback: Function) => void
  • Usage:
js
fApi.bus.$off('custom-event', handleCustomEvent);

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