Often do the background of small partners may often encounter a variety of form structures, input, SELECT, time, date plug-ins, etc., a variety of attribute configuration to the puke, today with you to encapsulate a reusable form. The form references some examples on the web and encapsulates its own business form component with its own requirements. First above:

First, let me show you the layout: we actually put a form. The el-Form-Item loop is then used to set dynamic label, dynamic rules, and corresponding prop for each el-Form-Item. We then add dynamically disabled properties to each type of form element to control the editable state. Bind properties to dynamic form values, and add placeholder hints; For form elements bound to multiple fields, such as SELECT and checkbox, the options attribute is provided in the configuration item. Then we upload the image using the image upload component we encapsulated earlier, passing a binding value and an editable status. Finally, we added a tooltip to each form element to remind the user of the content or prompt to fill in for each form element. For each label label, we also did the most basic thing, adding an ellipsis to a word that was larger than four, and using tooltip to see the label name.

<template> <div> <el-form :label-position="labelPosition" :inline="inline" :label-width="labelWidth" :model="myForm" ref="customForm"> <el-form-item v-for="(item,index) in formData" :label="returnLable(item.label)+':'" :rules="item.rules" :key="index" :prop="item.prop"> <el-tooltip v-if="item.type == 'input'" :effect="effect" :content="' please fill in '+item.label" placement="top"> <! -- prefix-icon --><! <el-input v-model="myForm[item.prop]" clearable :suffix-icon=" item.suficon ":show-password ="item.password" :prefix-icon="item.preIcon" :placeholder=" select '+item.label" :disabled="item.disabled"> </el-input> </el-tooltip> <el-tooltip V-if ="item.type == 'select'" :effect="effect" :content="' please select' +item.label" placement="top"> <el-select v-model="myForm[item.prop]" filterable clearable :multiple="item.multiple" filterable Options :placeholder=" select '+item.label" :disabled="item.disabled"> <el-option v-for="o in item.options" :key="o.value" :label="o.label" :value="o.value"> </el-option> </el-select> </el-tooltip> <el-tooltip v-if="item.type == 'radio'" <el-radio-group V-model ="myForm[item.prop]" :effect="effect" :content="' please select +item.label" placement="top"> <el-radio-group V-model ="myForm[item.prop]" :disabled="item.disabled"> <el-radio v-for="o in item.options" :label="o.value" {{O.label}}</el-radio> </el-radio-group> </el-tooltip> <el-tooltip V-if ="item.type == 'checkbox'" :effect="effect" :content="' please select '+item.label" placement="top"> <el-checkbox-group V-model ="myForm[item.prop]"  :disabled="item.disabled"> <el-checkbox v-for="o in item.options" :label="o.value" {{O.label}}</el-checkbox> </el-checkbox-group> </el-tooltip> <el-tooltip V-if ="item.type == 'date'" :effect="effect" :content="' please select '+item.label" placement="top"> <el-date-picker V-model ="myForm[item.prop]" Type ="date" value-format=" YYYY-MM-DD ":picker-options="pickerOptions" :placeholder="' select '+item.label" :disabled="item.disabled"> </el-date-picker> </el-tooltip> <el-tooltip v-if="item.type == 'datetime'" :effect="effect" <el-date-picker V-model ="myForm[item.prop]" type=" dateTime ":content="' please select '+item.label" placement="top"> Value -format=" YYYY-MM-DD HH: MM: SS ":picker-options="pickerOptions" :placeholder="' select '+item.label" default-time="12:00:00" :disabled="item.disabled"> </el-date-picker> </el-tooltip> <el-tooltip v-if="item.type == 'image'" :effect="effect" :content="' please select '+item.label" placement="top"> <upload-image V-model ="myForm[item.prop]" :disabled="item.disabled"></upload-image> </el-tooltip> </el-form-item> </el-form> <el-form v-if="isHandle" style="padding-left: 20px;" > <el-form-item> <slot name="handle"></slot> </el-form-item> </el-form> </div> </template>Copy the code

Here are the method and property definitions within the component

<script> import uploadImage from '@/mycomponents/UploadImage/index.vue' export default { components:{uploadImage}, FormName :{type:String, default:'right'}, // toolbar :{type:Boolean, default:true}, LabelPosition :{type:String, default:'right'}, // Tooltip style is dark or light effect:{type:String, Inline :{type:Boolean, default:true}, // form labelWidth labelWidth:{type:String, Default: '100 px'}, / / binding form myForm: {type: Object, the default () = > {}}, / / form configuration data formData: {type: Array, default: () = > []}}, data(){ return { pickerOptions : { shortcuts: [{ text: 'Today ', onClick(picker) {picker.$emit('pick', new Date())}}, {text: 'yesterday ', onClick(picker) {const date = new date () date.settime (date.gettime () -3600 * 1000 * 24) picker.$emit('pick', date) } }, { text: 'A week ago ', onClick(picker) { const date = new Date() date.setTime(date.getTime() - 3600 * 1000 * 24 * 7) picker.$emit('pick', If (label.length>4){return label.substring(0,4)+'... '} return label}, // Form validation async submitForm(prop) {try {return await this.$refs["customForm"].validate(); } catch (error) { return error; } }, } } </script>Copy the code

When we use it in the page, we just need to call the verification method to see if it passes the verification. The form verification method here returns a promise, so we use async and await to renturn the flag. Look again at our component application page; (See the Element documentation for the specific attributes here.)

<template> <div class="pages-container"> <dynamic-form :myForm="myForm" :formData="formData" ref="dynamic"> <div slot="handle"> <el-button type="primary" @click="onSubmit()">{{submitText}}</el-button> <el-button Type = "warning" > cancel < / el - button > < / div > < / dynamic - form > < div > submit status: {{text}} < / div > <! Form usage instructions --> <p> Basic usage defines a myForm (object collection of form-bound fields) </p> <p> Label :' user name',// Label name of the form element </p> <p>prop:'name', <p> <p> <p> <p> <p> <p> <p> <p> <p> <p> </p> <p>sufIcon: ",//input fields, etc. </p> <p> Rules :Check(true, null, 'blur',) </p> <p> 'User name cannot be empty '),// check rule, reference is a big god on the web encapsulation method. </ P > < P > < SPAN > Configuration item Attribute Type Value Definition :</ SPAN > < SPAN > Input: common input box </span> < SPAN >select: Dropdown box </ SPAN > <span>radio: radio: radio </span> <span>checkbox: checkbox </span> <span> Date: date </span> <span>dateTime: <span> <span>image: Picture < / span > < / p > < / div > < / template > < script > import DynamicForm from '@ / mycomponents/Form/dynamic vue' import {Check} from '@/utils/rule.js' export default { components:{DynamicForm}, data(){ const options = [{ value: '1', label: 'yellow golden cake'}, {value: '2', label: 'double peel milk'}, {value: '3', label: 'oyster omelet}, {value:' 4 ', label: "dragon beard noodles"}, {value: '5', the label: 'Peking duck' return {}] the text: "', submitText: 'editing', / / form value binding myForm: {name:" ', vscode: "', prodType:" ', prodp: '2', commissions:['1','5'], commdate:'', commdatetime:'', images:['https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80'], }, FormData :[{label:' user name',// Label name prop:'name',// field value type:'input',// form element type PreIcon :'el-icon-search',// header tag, Input element unique rules:Check(true, null, 'blur', 'username cannot be empty '),// validation rules disabled:true,}, {label:' admin password ', prop:'vscode', Type :'input', sufIcon:'',// Rules :Check(true, null, 'blur', 'password cannot be empty '), disabled:true,}, {label:' product type ', Prop :'prodType', type:'select', rules:Check(true, null, 'change', 'please select product type '), options:options, Multiple :false,//select Disabled :true,}, {label:' product category ', prop:'prodp', type:'radio', rules:Check(true, null, 'change', 'Please select product category '), options:options,// Property option values disabled:true,}, {label:' Order selection ', prop:' -Commissions ', type:'checkbox', Rules :Check(true, null, 'change', 'please order select '), options:options,// Property options value disabled:true,}, {label:' order date', prop:' commDate ', Type :'date', rules:Check(true, null, 'change', 'please select order date'), disabled:true,}, {label:' order datetime', prop:' commDateTime ', Type :'datetime', rules:Check(true, null, 'change', 'please select order date and time'), disabled:true,}, {label:' order icon ', prop:'images', Type :'image', rules:Check(true, null, 'change'), disabled:true,},]}}, mounted() {}, methods:{// click submit. Async onSubmit(){if(this.submitText == 'edit '){this.formData.foreach (item=>{item.disabled = false; }) this.submitText = 'submit'}else{this.formData.foreach (item=>{item.disabled = true; This.submittext = 'edit'}) let flag = await this.$refs.dynamic.submitForm(); if(flag){ this.text = "success submit" }else{ this.text = "fail submit" } } }, } } </script>Copy the code

My rules check method is on the Internet to see a great god of the check method, understand the details, use it, give you a look.

//Check method //Check rule list (extensible) const rules = {URL(URL) {const regex = /^(HTTPS? |ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?) (\. (25 [0 to 5] | 2 [0 to 4] [0-9] [0-9] {2} | 1 | [1-9]? [0-9])){3}|([a-zA-Z0-9-]+\.) *[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA- Z0-9.,? \ \ "+ & % $# = ~ _ -] +)) * $/ return valid (url, regex," url format is not correct ")}, LowerCase(STR) {const regex = /^[a-z]+$/ return Valid (STR, regex, "LowerCase only ")}, UpperCase(STR) {const regex = /^[a-z]+$/ return Valid (STR, regex, "UpperCase only ")}, Alphabets(STR) {const regex = /^[a-za-z]+$/ return valid(STR, regex, "only letters ")}, Email(email) { const regex = (([/ ^ ^ < > () \ [\] \ \,; : \ s + (\. @ "] [^ < > () \ [\] \ \,; : \ s @ "] +) *) | (" + ")) @ ((\ [[0-9] {1, 3} \. [0-9] {1, 3} \. [0-9] {1, 3} \. [0-9] {1, 3} \]) | ((( a-zA-Z\-0-9]+\.) + [a zA - Z] {2})) $/ return valid (email, regex, "email address format is not correct")}, Mobile(Mobile) {const regex = /^1\d{10}$/ return valid(Mobile, regex, "Mobile number format is incorrect ")}, Const regex = /^(0\d{2,3})? -? \d{7,8}$/ return valid(phone, regex, "phone number format is incorrect ")}, Postcode(Postcode) {const regex = /^[0-9][0-9]{5}$/ return Valid (Postcode, regex, "Postcode format is incorrect ")}, Number(num) {const regex = /^\d+$/ return valid(num, regex, "only pure digits ")}, Fax(Fax) {const regex = /^(\d{3,4}-)? \ d {7, 8} $/ return valid (fax, regex, "fax format is not correct")}, Int (num) {const regex = / ^ ((0) | (\ [1-9] d *)) $/ return valid (num, regex, IntPlus(num){const regex = /^[1-9]\d*$/ return Valid (num, regex, "only positive integer ")}, IntPlus(num){const regex = /^[1-9]\d*$/ return Valid (num, regex," only positive integer ")}, Float1(num){ const regex = /^-? \d+(\.\d)? $/ return Valid (num, regex)}, Float2(num){const regex = /^-? \ d + (\ \ d {1, 2})? $/ return Valid (num, regex, "only two decimal digits ")}, Float3(num){const regex = /^-? \ d + (\ \ d {1, 3})? $/ return valid(num, regex)}, FloatPlus3(num){const regex = /^\d+(\.\d{1,3})? $/ return valid(num, regex)}, FloatPlus3(num){const regex = /^\d+(\.\d{1,3})? $/ return Valid (num, regex," Up to three decimal places ")}, Encode (code) {const regex = / ^ (_ | - | [a - zA - Z0-9]) + $/ return valid (code, regex, "in the code can only use letters, Numbers, underscores, crossed")}, Encode2(code){const regex = /^[a-za-z0-9]+$/ return valid(code, regex, "Only letters and numbers ")}, Encode3 (code) {const regex = / ^ (_ | [a - zA - Z0-9]) + $/ return valid (code, regex, "encoding to use only letters, Numbers, underscores,")}, IdCard(code){ const regex = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/ return valid(code, }, USCC(code){const regex = /^[0-9a-z]{18}/ return valid(code, regex, "please input correct social credit number ")}, CarNum(code){ const regex = / ^ (([beijing-tianjin Shanghai yu ji yu cloud liao black xiang anhui new GuiGan of hubei province can Sue your yue jin meng shan ji min qinghai-tibet plain NingQiong make led] [a-z] ([[0-9] {5} [DF]) | ([DF], [A - HJ - NP - Z0-9]] [0-9] {4}))) | ([the Beijing and tianjin only black new xiang wan lu su liao ji yu cloud of hubei province can GuiGan jin meng shan ji min expensive Guangdong qinghai-tibet plain NingQiong make led] [a-z] [A - HJ - NP - Z0-9] {4} [A - HJ - NP - Z0 - hang cop Hong Kong and Macao to bring]) $/ I return valid (code, regex, "please enter the correct license plate number")}, CNandEN(code){const regex = /^[a-za-z \ u4e00-u9fa5]+$/ return Valid (code, regex, "u4e00-u9fa5 ")}, MobileOrPhone (val) {const result = / ^ 1 \ d {10} $/. The test (val) | | / ^ (0 \ d {2, 3})? -? \ d {7, 8} $/. The test (val) return valid (result, null, "Mobile phone or telephone number format is not correct")}} / / val: the value of the String to check / / regex: RegExp check regular, not regular val / / MSG: as a result of the value String check without error message function valid (val,  regex, msg){ return {result: regex instanceof RegExp? regex.test(val) : !! val, errMsg: MSG}} //required:Boolean Mandatory, optional, default "true" //type:String/Function Check type, optional, // String must be the Function name existing in rules above, // Function takes only one argument (input value) and returns the following format: {result:Boolean, errMsg:String} //trigger:String action, optional, default "blur" //nullMsg:String untyped prompt, optional, Export function Check(required=true, type, trigger="blur", NullMsg =" This field is required "){const rule = {required:!! required, trigger} let check = null if(typeof type === "function"){ check = type }else{ check = type ? rules[type+""] : Null} if(check){// Add a rule rule-validator = (r, v, c) => {const {result, errMsg} = check(v) if(required){// Mandatory: Null, and undefined, ""," "is no input return (v = = null | | (v +" "). The trim () = = = "")? c(new Error(nullMsg)) : result ? (c) : c (new Error (errMsg)} / / optional: null, and undefined, "" is no input," "will be checking the return (v = = null | | (v +" ") = = = "" | | result)? c() : c(new Error(errMsg)) } }else{ rule.message = nullMsg } return [rule] }Copy the code

The check method is perfect.

At this point, we’re done wrapping a simple form form. If you need it, you can add more elements, such as switches, radio-buttons and so on. The encapsulated elements here are only the most basic elements. If you want more elements, you can add them by yourself. Everyone think helpful to you, you can point a thumbs-up!! Thank you very much!!