element UI
The form form dynamically adds or subtracts form items
Recently, WE received a demand for user-defined form items and needed to verify the new items. In this project, we adopted the UI component element, so we used the built-in Form component to realize functions. However, we found a pit and struggled for one or two hours
Here is an example from the official website
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm"> <el-form-item v-for="(domain, Index) in dynamicValidateForm. Domains: "label =" 'domain' + index "is: the key =" domain. The key ": prop = 'domains.'" + index + 'value'" :rules="{required: true, message: 'Domain name cannot be empty ', trigger: 'blur' }" > <el-input v-model="domain.value"></el-input> </el-form-item> </el-from> <script> export default { data() { return { dynamicValidateForm: { domains: [{ value: '' }], email: '' } }; }, } </script>Copy the code
If you do not set the prop property according to this format, you will find no matching value, or the verification rule is always error, will not pass the verification.
:prop="'domains.' + index + '.value'"
Copy the code
Domains are the key of the loop body below the form from binding value, index is the current subscript, and value is the key of the V-modal binding of the current loop object.
Let’s go back to the Element UI source code and see how it matches this prop
fieldValue() { const model = this.form.model; if (! model || ! this.prop) { return; } let path = this.prop; if (path.indexOf(':') ! == -1) { path = path.replace(/:/, '.'); } return getPropByPath(model, path, true).v; }Copy the code
So what we see here is that he’s getting the matching value through this getPropByPath method, three parameters, the first one is the binding value of our form, The second is the prop bound to formItem (prop=”‘domains.’ + index + ‘.value'”)
Here’s the specific getPropByPath matching method
export function getPropByPath(obj, path, strict) { let tempObj = obj; path = path.replace(/\[(\w+)\]/g, '.$1'); path = path.replace(/^\./, ''); let keyArr = path.split('.'); let i = 0; for (let len = keyArr.length; i < len - 1; ++i) { if (! tempObj && ! strict) break; let key = keyArr[i]; if (key in tempObj) { tempObj = tempObj[key]; } else { if (strict) { throw new Error('please transfer a valid prop path to form item! '); } break; } } return { o: tempObj, k: keyArr[i], v: tempObj ? tempObj[keyArr[i]] : null }; };Copy the code
Please transfer a valid prop path to form item! The reason is that prop did not match the data. The rule of prop is to iterate through the binding value of prop, return if found, and throw an error if not found