Skip to content

Prototype Methods

FormCreate provides a series of global methods. This guide details the usage methods, configuration instructions, and helps new users get started quickly through examples.

How to Call Global Methods

Before using these methods, ensure formCreate has been imported. The following is an example of how to import and use FormCreate's global methods in your project.

Import FormCreate

First, make sure you have installed FormCreate and imported it in your project:

js
import { createApp } from 'vue';
import App from './App.vue';
import formCreate from '@form-create/element-ui'; // Choose the corresponding package based on your UI framework
const app = createApp(App);
app.use(formCreate);
app.mount('#app');

Call Global Methods

In your components or applications, access and call global methods through the formCreate object. The following are some examples of common method calls:

js
const api = formCreate.getApi('formName');

Global Methods

The following contains detailed information about form operation methods, JSON conversion methods, component and extension methods, data processing methods, and advanced extension methods:

方法名类型描述
create(rules: Rule[], options: object) => Api生成表单实例,返回表单API对象,用于动态控制表单。
getApi(name: string) => Api | Api[]通过表单名称获取表单API实例。
copyRules(rules: Rule[]) => Rule[]拷贝生成规则数组,避免影响原始规则。
copyRule(rule: Rule) => Rule拷贝单个生成规则,避免影响原始规则。
toJson(value: Rule[] | object) => string将生成规则转换为JSON字符串,方便存储和传递。
parseFn(fnString: string) => Function将函数字符串转换为函数对象。
parseJson(json: string) => Rule[] | object将JSON字符串转换为表单生成规则,恢复表单结构。
$form() => Component获取FormCreate组件实例,用于手动挂载到应用中。
component(name: string, component?: Component) => Component | undefined挂载或获取自定义组件。
componentAlias(alias: {[aliasName: string]: string}) => void为组件设置别名,简化生成规则中的引用。
setModelField(componentName: string, propName: string) => void设置自定义表单组件值的双向绑定字段名称(默认modelValue)。
directive(name: string, directive: Directive) => void挂载自定义指令。
setData(name: string, value: any) => void挂载自定义数据,供表单组件共享。
setDataDriver(id: string, callback: (key: string) => any) => void导入自定义数据获取函数,支持从外部数据源动态获取数据。
getData(name: string) => any获取通过setData挂载的自定义数据。
removeData(name: string) => void移除通过setData挂载的自定义数据。
refreshData(name: string) => void手动刷新与特定数据相关的表单渲染。
fetch(options: { action: String, method?: String, ... }) => void内置数据请求方法,支持重写以处理异步数据。
extendApi(fn: (api: Api) => Object) => void扩展表单API,添加自定义操作方法。
parser(name: string, parser: Parser) => void为表单组件绑定自定义解析器,处理特殊数据格式或转换逻辑。
register(name: string, effect: Effect) => void注册自定义属性扩展,生成规则时自动执行逻辑。
factory() => FormCreate创建全新的formCreate实例。
use(fn: (formCreate: FormCreate, opt: object) => FormCreate) => void安装formCreate插件(需提供install方法)。
useApp(fn: (formCreate: FormCreate, app: App) => void) => void组件初始化时通过app回调。

Form Operation Methods

create

Generates a form instance and returns the form's API object for further form operations.

  • Type:
ts
type Create = (rules:Rule[], options:object) => Api;
  • Example:
js
const rules = [
    { type: 'input', field: 'name', title: 'Name', value: '' },
    { type: 'input', field: 'email', title: 'Email', value: '' }
];


const options = {
    onSubmit: (formData) => {
        console.log('Form Submitted', formData);
    }
};


const api = formCreate.create(rules, options);

The create method generates a form through a rules array and lets you configure form behavior (such as submit events, initial values, etc.) through options. The returned api is a form API object that you can use to dynamically control the form.

getApi

Get the form's API instance through the form's name. This is useful when you need to operate on specific forms across components or in large applications.

  • Type:
ts
type GetApi = (name:string) => Api | Api[];
  • Example:
html
<form-create name="form" :rule="rule" />
js
const api = formCreate.getApi('form')

copyRules

Copy an array of generation rules, ensuring changes to rules don't affect the original rules.

  • Type:
ts
type CopyRules = (rules:Rule[]) => Rule[];
  • Example:
js
const rules = formCreate.copyRules([{
  type:'input',
  field:'goods_name',
  title:'Product Name',
  value:'form-create'
}])

copyRule

Copy a single generation rule, ensuring changes to the rule don't affect the original rule.

  • Type:
ts
type CopyRule = (rule:Rule) => Rule;
  • Example:
js
 const rule = formCreate.copyRule({
  type:'input',
  field:'goods_name',
  title:'Product Name',
  value:'form-create'
})

JSON Conversion Methods

toJson

Convert specified generation rules to JSON string for easy storage and transfer.

  • Type:
ts
type ToJson = (value:Rule[]|object) => string;
  • Example:
js
const rules = [
    { type: 'input', field: 'goods_name', title: 'Product Name', value: 'form-create' }
];
const json = formCreate.toJson(rules);
console.log(json); // Output JSON string

parseFn

The parseFn method converts a function string to a function object.

  • Type:
ts
type ParseFn = (fnString:string) => Function;
  • Example:
js
const fn = formCreate.parseFn(`function() {
    console.log('This is a function');
}`);

parseJson

Convert JSON string to form generation rules for restoring form structure.

  • Type:
ts
type ParseJson = (json:string) => Rule[]|object;
  • Example:
js
const json = '{"type":"input","field":"goods_name","title":"Product Name","value":"form-create"}';
const rules = formCreate.parseJson(json);

Component and Extension Methods

$form

Get the FormCreate component instance, usually used for manual mounting to applications.

  • Type:
ts
type $form = () => Component;
  • Example:
js
const $formCreate = formCreate.$form();
app.component('form-create', $formCreate);

component

Mount or get custom components in FormCreate.

  • Type:
ts
type Component = (name: string, component?: Component)=> Component|undefined;
  • Example:
js
//Mount component
formCreate.component('user',component)
//Get component
const component = formCreate.component('user')

componentAlias

Set aliases for components, making it easier to reference components with simpler names in generation rules.

  • Type:
ts
type ComponentAlias = (alias:{[aliasName:string]:string }) => void;
  • Example:
js
formCreate.componentAlias({btn:'ElButton'})

setModelField

Set the two-way binding field name for custom form component values, default is modelValue.

ts
type SetModelField = (componentName:string,propName:string) => void;
  • Example:
js
formCreate.setModelField('input','value');

directive

Mount custom directives in FormCreate.

  • Type:
ts
type Directive = (name:string, directive:Directive) => void;
  • Example:
js
formCreate.directive('autofocus',(el) => {
  el.focus();
})

Data Processing Methods

setData

Mount custom data to make it available in forms, facilitating data sharing between components.

  • Type:
ts
type SetData = (name:string,value:any) => void;
  • Example:
js
 formCreate.setData('options',[
        {label:'Easy to use',value:0},
        {label:'Fast',value:1},
        {label:'Efficient',value:2},
        {label:'All-in-one',value:3},
 ]);

setDataDriver

Import custom data retrieval functions to retrieve data from external data sources based on specific logic.

  • Type:
ts
type SetDataDriver = (id: string, callback: (key: string) => any) => void;
  • Example:
js
formCreate.setDataDriver('$user', function(key) {
    return $store.state.user[key];
});

The setDataDriver method lets you specify a data driver function for forms, enabling form components to dynamically retrieve data. For example, retrieve user data from Vuex state management and display it in forms.

getData

Get custom data previously mounted through setData.

  • Type:
ts
type GetData = (name: string) => any;
  • Example:
js
const options = formCreate.getData('options');
console.log(options);

removeData

Remove custom data previously mounted through the setData method.

  • Type:
ts
type RemoveData = (name:string) => void;
  • Example:
js
formCreate.removeData('options');

refreshData

Manually refresh form rendering related to specific data, ensuring form component display and data remain synchronized.

  • Type:
ts
type RefreshData = (name:string) => void;
  • Example:
js
formCreate.refreshData('options');

fetch

Built-in data request method in FormCreate, supports rewriting for convenient handling of asynchronous data.

  • Type:
ts
type Fetch = (options: {
  //Interface
  action: String;
  //Request method
  method?: String;
  //Data attached to interface call
  data?: object;
  //Submission method for data attached to interface call, default is `formData`
  dataType?: 'json';
  //Custom header information
  headers?: object;
  //Interface call success callback
  onSuccess: (body: any) => void
  //Interface call failure callback
  onError?: (e: Error | ProgressEvent) => void;
})=> void;
  • Example
js
formCreate.fetch({
  action: 'https://api.example.com/data',
  method: 'POST',
  data: { key: 'value' },
  onSuccess: (response) => {
    console.log('Data fetched', response);
  },
  onError: (error) => {
    console.error('Error fetching data', error);
  }
});

Advanced Extension Methods

extendApi

Extend formCreate's form API, adding custom form operation methods.

  • Type:
ts
type ExtendApi = (fn:(api: Api)=>Object) => void;
js
formCreate.extendApi((api) => ({
  open(id) {
    console.log('This is a custom method');
    api.top.el(id).open();
  }
}));

parser

Bind custom parsers to form components to handle special data formats or conversion logic.

  • Type:
ts
type Parser = (name:string,parser:Parser) => void;
  • Example:
js
formCreate.parser({
    name:'input',
    toFormValue(val){
        return parseFloat(val)||0
    }
})

register

Register custom attribute extensions, enabling automatic execution of certain logic when generating rules.

  • Type:
ts
type Register = (name:string, effect:Effect) => void;
  • Example:
js
formCreate.register('loadOptions', {
  component:'select',
  init(rule){
      rule.props.options = [
        {label:'Easy to use',value:0},
        {label:'Fast',value:1},
        {label:'Efficient',value:2},
        {label:'All-in-one',value:3},
      ];
  }
})

factory

Create a brand new formCreate instance

  • Type:
ts
type Factory = () => FormCreate;
  • Example:
js
const subFormCreate = formCreate.factory()

use

Install formCreate plugin. If the plugin is an object, it must provide an install method. If the plugin is a function, it will be used as the install method. When the install method is called, formCreate is passed as a parameter. This method must be called during plugin initialization.

  • Type:
ts
type Use = (fn: (formCreate:FormCreate, opt:object) => FormCreate) => void;

useApp

Component initialization is called back through app

  • Type:
ts
type UseApp = (fn: (formCreate:FormCreate, app:App)=>void ) => void;

Examples

JSON Parsing

Use FormCreate's JSON serialization and parsing functionality: convert form rules to JSON strings through formCreate.toJson(), and restore form rules from JSON strings through formCreate.parseJson().

vue
<template>
    <form-create :rule="rule" :option="options"/>
    <el-button @click="getJSON">获取表单 JSON</el-button>
    <el-button>JSON 转表单规则</el-button>
</template>
<script setup>
    import {ref} from 'vue';
    import formCreate from '@form-create/element-ui';
    function getJSON() {
        return formCreate.toJson(rule.value);
    }
    function loadJSON() {
        rule.value = formCreate.parseJson('[{"type":"input","field":"Flbgmcge0qdfacc","title":"输入框"},{"type":"input","field":"F6g2mcge0qktahc","title":"多行输入框","props":{"type":"textarea"}}]')
    }
    const rule = ref([
        {
            type: 'input',
            field: 'goods_name',
            title: '商品名称',
            value: 'form-create'
        },
        {
            type: 'checkbox',
            field: 'label',
            title: '标签',
            value: [0, 1, 2, 3],
            options: [
                {label: '好用', value: 0},
                {label: '快速', value: 1},
                {label: '高效', value: 2},
                {label: '全能', value: 3},
            ]
        },
        {
            type: 'el-button',
            title: '自定义按钮',
            native: false,
            on: {
                click() {
                    alert('点击了按钮')
                }
            },
            children: ['按钮']
        },
    ]);
    //表单配置
    const options = ref({
        onSubmit: (formData) => {
            alert(JSON.stringify(formData))
        },
        form: {
            labelPosition: 'top'
        },
        resetBtn: true
    });
</script>

Importing External Data

Use the formCreate.setData() method to import external data (such as user token) into the form context, enabling form components to access and use this global data, achieving dynamic data binding and interaction.

vue


<template>
    <form-create :rule="rule" :option="options"/>
</template>
<script setup>
    import {ref} from 'vue';
    import formCreate from '@form-create/element-ui';
    formCreate.setData('token', getToken());
    const rule = ref([
        {
            type: 'input',
            field: 'goods_name',
            title: 'Product Name',
            value: 'form-create'
        },
        {
            type: 'checkbox',
            field: 'label',
            title: 'Label',
            value: [0, 1, 2, 3],
            options: [
                {label: 'Easy to use', value: 0},
                {label: 'Fast', value: 1},
                {label: 'Efficient', value: 2},
                {label: 'All-in-one', value: 3},
            ]
        },
        {
            type: 'el-button',
            title: 'Custom Button',
            native: false,
            on: {
                click() {
                    alert('Button clicked')
                }
            },
            children: ['Button']
        },
    ]);
    //Form configuration
    const options = ref({
        onSubmit: (formData) => {
            alert(JSON.stringify(formData))
        },
        form: {
            labelPosition: 'top'
        },
        resetBtn: true
    });
</script>

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