Core requirements for form components
Collect, verify and submit data
The layered design
El-form, el-form-item, el-input, etc
Job analysis
1. El-input: data is bound to the attributes of model, and the verification is triggered to bind data bidirectionally through V-Model; Send el-form-item to emit events via dispatch.
<template> <div ... > <input ... @blur="hanldeBlur">
</div>
</template>
<script>
exportdefault { methods: { ... .handleBlur() {
this.dispatch('ElFormItem'.'el.form.blur', [this.value]); },... } } </script>Copy the code
This. Dispatch is an emitter from mixins, and it emit(” elform.blur “,…) from the emitter. This. Dispatch is an emitter from mixins, and it emit(“el.form.blur”,… Then ElFormItem checks by listening for the el.form.blur event.
El-form-item: Displays error messages based on the mounted listening event (el.form.blur). At the same time, it also saves itself in the EL-form through Dispatch, so that the el-form can validate the whole form.
<template> <div> <label ... ></label> <div> <slot></slot> </div> <div> <template> <script>exportdefault { methods: {validate(trigger, callback = noop) {validate(trigger, callback = noop) {validate(trigger, callback = noop) {onFieldBlur() {
this.validate('blur');
},
addValidateEvents() {
this.$on('el.form.blur', this.onFieldBlur); }},mounted() {
this.dispatch('ElForm'.'el.form.addField', [this]);
this.addValidateEvents()
}
}
</script>
Copy the code
3. El-form: Set the data object and verification rules of the form, and actively trigger the verification of the form.
<script>
export default {
provide() {
return {
elFormItem: this
};
},
props: {
model: Object,
rules: Object,
...
},
method: {
validate(callback) {
this.fields.forEach(field => {
field.validate(' ', (message, field) => { ... }); }); }},created() {
this.$on('el.form.addField', (field) => {
if(field) { this.fields.push(field); }}); } } </script>Copy the code
serendipity
El-form-item rules are also acceptable in API documents, but when both el-form rules and El-form-item rules are specified, el-form-item rules are preferred.
getRules() {
letformRules = this.form.rules; const selfRules = this.rules; .return [].concat(selfRules || formRules || []).concat(requiredRule);
}
Copy the code
Common tips for component libraries
These mixins can be used to implement things like bubbling and broadcasting
2. Provide/Inject implement attribute transfer across multiple layers
3. Publish-subscribe uses Dispatches from Emitter.
El-form also uses scope slots to display custom errors
conclusion
El-form is a good component source analysis to start, code design ideas are clear, using the basic API and knowledge points.
Component design principles for reference: engineering.carsguide.com.au/front-end-c…