More articles
preface
Before we start, let’s talk a little bit about the Form component. A Form component is a Form generated from a configuration file, which can be easily understood as a dynamic Form
introduce
According to the existing business to encapsulate the logical layer of the Form, useForm needs to be used together with the Form encapsulated by us. If it does not meet the requirements, it can check and fill the gaps
Based on using
Form component is the encapsulation of UI layer, useForm is the supporting logical layer, except for the very personalized business through slot processing, the rest are through data configuration (formConfig) and logical layer to complete the DISPLAY effect of UI layer
<template> <Form ref="formRef" :formData="formData", :formConfig="formConfig" > <el-button @click="searchFormHandle"> search </el-button> </Form> </template> <script> import {ref } from '@vue/composition-api' import Form from '@/components/form' import useForm from '@/hooks/useForm' export default { components: { Form }, setup() { // ref const formRef = ref() // form const { formData, formConfig, submitHandle } = useForm({ formRef, formData: { member: undefined, time: undefined }, formConfig: [ { type: 'input', key: 'member', label: 'member', {type: 'datePicker', key: 'time', label: 'time', kind: 'daterange'},]}) // Search const searchFormHandle = () => submitHandle(() => console.log(' start calling interface ')) return {formRef, formData, formConfig, searchFormHandle } } } </script>Copy the code
The ginseng
For example, if inputNumber is used as an example, you can configure min and Max: {type: ‘inputNumber’, min: 0, Max: 10}. The configuration of the Form component only applies to the current scenario
parameter | instructions | type | An optional value | The default value |
---|---|---|---|---|
formRef | form-ref | VueComponent | – | – |
formData | Form data, same as the model with the Element-form binding | Object | – | – |
formConfig | Form display configuration, refer to the Form component, the same configuration as element forms | Arrary | – | – |
formRules | Form verification rules, refer to element verification rules | Object | – | – |
The ginseng
The formData, formConfig, and formRules thrown here are all reactive data
parameter | instructions | type | An optional value | The default value |
---|---|---|---|---|
formData | Form data, same as the model with the Element-form binding | Object | – | – |
formConfig | Form display configuration, refer to the Form component, the same configuration as element forms | Arrary | – | – |
formRules | Form verification rules, refer to element verification rules | Object | – | – |
submitHandle | Submit the form | Function:Promise(callback) | – | – |
resetHandle | Reset form & validation (element-form-resetFields method) | Function | – | – |
validateField | Partial validation (Element-form-validateField method) | Function(props: array/string) | – | – |
clearValidate | Clear validation (element-form-validateField method) | Function(props: array/string) | – | – |
resetFormConfig | Resetting formConfig(resetting to initialize the incoming configuration) | Function | – | – |
resetFormData | Resetting formData(resetting to initialize incoming formData) | Function | – | – |
setConfigs | Update the entire formConfig | Function(vals: Arrary) | – | – |
setConfig | Updates the property state of a configuration item in formConfig | Function(key, attr, value) | – | – |
getConfig | Gets a formConfig entry | Function(key) | – | – |
setFormItem | Assign a value to formData | Function(key, value) | – | – |
setFormRule | FormRules Specifies a verification rule | Function(key, index, value) | – | – |
setFormRuleAttr | Set formRules to a state | Function(key, index, attr, value) | – | – |
loopFormConfig | Traverse loopFormConfig | Function(callback(item)) | – | – |
loopFormData | Traverse loopFormData | Function(callback(formData, key)) | – | – |
SubmitHandle can be called either through callback or as a Promise
// callback
submitHandle(() = > console.log('I'm a callback function that executes if it passes the check.'))
// promise
submitHandle().then(valid= > valid && console.log('I'm calling it from the interface. If it passes the check, it will execute.'))
Copy the code
ResetFormData is mainly used to solve the problem that resetHandle cannot reset data. Usually, when the form class data is returned, the source data will be manipulated, causing the resetHandle cannot achieve the desired effect. ResetFormData is used to solve this problem
SetConfig: Suppose you want to set the disabled state of an input in different cases at this time
// Disabled is true when the id is 1
setConfig('member'.'disabled', id === 1)
Copy the code
SetFormRule: When a large number of configurations are configured, the configuration is referred to a configuration file. When the verification rule requires reactive formData, the static configuration file cannot obtain the real-time reactive data. Therefore, you need to use setFormRule to dynamically set the verification rule
setFormRule('pass'.1, {
validator: (rule, value, callback) = > {
const { formData: { pass, rePass } } = formState
if (creditAmount && orderAmount) {
if(pass ! == rePass) { callback(new Error('Two different passwords'))
return
}
}
callback()
},
trigger: ['blur'.'change']})Copy the code
SetFormRuleAttr: Dynamically sets an item to be checked or not checked
// This parameter is mandatory if the ID is 1
setFormRuleAttr('member'.0.'required', id === 1)
Copy the code
LoopFormConfig: Display all input boxes during editing, and display text after editing
const kinds = { default: 'text'.edit: 'input' }
const kind = 'edit'
loopFormConfig(item= > { item.type = kinds[kind])
Copy the code
LoopFormData: When editing the output, the data returned by the interface is messy. You can use loopFormData to complete the output
loopFormData((formData, key) = > {
if(! data[key])return
formData[key] = data[key]
})
Copy the code
The source code
import { reactive, toRefs } from '@vue/composition-api'
import { deepCopy } from '@/utils/qjd'
/** * scenarios: apply to all form class submission including query, with components/ QJD /form use, currently components only encountered scenarios, what is missing, according to the actual scenario extension useForm *@param formRef form-ref
* @param FormData Initializes data *@param FormConfig Form configuration *@param FormRules Verification rule */
export default ({
formRef,
formData,
formConfig,
formRules
}) => {
const state = reactive({
formData: deepCopy(formData),
formConfig: deepCopy(formConfig),
formRules: deepCopy(formRules)
})
// Submit the form
const submitHandle = async (callback = null) = > {try {
const { value: { submitHandle: forSubmit } } = formRef
const valid = await forSubmit()
valid && callback && callback(state.formData)
return valid
} catch (error) {
console.log(`error: ${error}`)}}// Reset the form
const resetHandle = () = > formRef.value && formRef.value.resetHandle()
// Verify some fields of the form
const validateField = val= > formRef.value && formRef.value.validateField(val)
// Clear checksum
const clearValidate = val= > formRef.value && formRef.value.clearValidate(val)
/ / query formConfig - item
const getConfig = key= > state.formConfig.find(item= > item.key === key)
// Update the entire formConfig
const setConfigs = vals= > { state.formConfig = deepCopy(vals) }
/ * * *@param key formConfig - key
* @param Attr formConfig - Property *@param Value Specifies the value */
const setConfig = (key, attr, value) = > {
if(! key || ! attr)return
const item = getConfig(key)
if(! item)return
item[attr] = value
}
// formData single element assignment
const setFormItem = (key, value) = > {
if(! key)return
state.formData[key] = value
}
// formRules Single attribute configuration changes
const setFormRuleAttr = (key, index, attr, value) = > {
if(! key || ! attr)return
state.formRules[key][index][attr] = value
}
/ / formRules a single configuration changes, in view of the need to dynamically set the validation rules | check rules depend on the response of the form data
const setFormRule = (key, index, value) = > {
if(! key)return
state.formRules[key][index] = value
}
// Iterate through formConfig and process data through callBAC
const loopFormConfig = (callback) = > state.formConfig.forEach(item= > callback && callback(item))
// Iterate over formData and process the data through callBAC
const loopFormData = (callback) = > Object.keys(state.formData).forEach(key= > callback && callback(state.formData, key))
/ / reset formData
const resetFormData = () = > { state.formData = deepCopy(formData) }
/ / reset formConfig
const resetFormConfig = () = > { state.formConfig = deepCopy(formConfig) }
return{ submitHandle, resetHandle, validateField, clearValidate, setConfigs, setConfig, getConfig, setFormItem, setFormRuleAttr, setFormRule, loopFormConfig, loopFormData, resetFormData, resetFormConfig, ... toRefs(state) } }Copy the code
conclusion
Form is also a relatively complex piece, currently has temporary functions as above, need to continue to improve in business development