In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Vue how to form verification (form) validate, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.
1. Principle explanation
Consider
Let's see, we can use form to trigger the check as a whole or a single input to trigger the form-item to check the children's shoes. Now they may still feel that they don't understand, so it's okay to move on.
two。 Distribution and broadcast
Why use radio and distribution. In general, we try not to use vuex and bus (event bus) for components that have nothing to do with the business. Next I send the code for broadcast and distribution. We tie this.$on ('event',res= > ()) to the calling component and call $emit through dispatch and broadcast.
Dispatch is to look up and only call 1
The broadcast is to look down and call multiple
Note that all components of ⚠️ should be written with name
Using the mixer mixins
Emitter.js/** * recursively uses call to point to * @ param componentName / / the name of the component to be found * @ param eventName / / event name * @ param params / / the parameter to be passed * / function broadcast (componentName, eventName) Params) {/ / cycle child node to find a child node with the same name or recursive current child node this.$children.map (child= > {if (componentName===child.$options.name) {child.$emit.apply (child, [eventName] .concat (params))} else {broadcast.apply (child, [componentName) EventName] .concat (params)}} export default {methods: {/ * dispatch (look up) (one) * @ param componentName / / name of the component to be found * @ param eventName / / event name * @ param params / / Parameter to be passed * / dispatch (componentName, eventName, params) {let parent = this.$parent | | this.$root / / $parent find the nearest parent node $root root node let name = parent.$options.name; / / get the name of the current component instance / / if there is a node & & currently has no name and the current name is equal to the name that needs to be passed in, find the current node / / cycle out the current name of the same component instance while (parent & & (! name | | nameplate component instance name) {parent = parent.$parent If (parent) {name = parent.$options.name }} / / A node indicates that an instance like name has been found: if (parent) {parent.$emit.apply (parent, [eventName] .concat (params))}} / * broadcast (look down) (broadcast multiple) * @ param componentName / / the name of the component to be found * @ param eventName / / event name * @ param params / / parameters to be passed * / broadcast (componentName, eventName, params) {broadcast.call (this,componentName, eventName, params)}
3.async-validator
If you don't understand async-validator, you can check github on the official website.
Yarn add async-validator / / because the current plug-in needs to be packaged into the project, you cannot add-D
4.api design
Let's take a look at the picture of element's official website below.
Form has two injected fields: rules rule, and: model the value of the current form is verified by matching the value of model with rules.
Form-item has two injected fields lable and prop (prop) to match with form to get the value of the current form-item
Input actually has the current @ input method. V-model won't explain.
Form
Let's start injecting all the current form-item instances in form (get)
Created binds and deletes the methods of the current instance at the beginning of the life cycle. Usually, bindings are called before the page dom starts and need to be loaded by dom.
Provide is used with inject to allow child components to call methods of the current parent component as well as data
The following notes are written for safe consumption (after testing, they can be verified at present)
Form.vue export default {name: "aiForm", provide () {/ / [https://cn.vuejs.org/v2/api/#provide-inject) return {form: this}}, props: {type: Object} of the current form, / / verify rules: {type: Object}} Data () {return {fields: [] / store the current form-item instance}}, created () {/ / save the current instance let that = this This.$on ('on-form-item-add',item= > {if (item) {that.fields.push (item)}}) / / delete the current instance this.$on ('on-form-item-remove',item= > {if (item.prop) {/ / if there is no prop currently, do not delete (because there is no injection) that.fields.splice (that.fields.indexOf (item), 1)}})})} Methods: {/ * clear * / resetFields () {/ / add resetFields method to be called / * all current assignment when form-item * / this.fields.forEach (field = > {field.resetField ()) Promise * / validate (callback) {return new Promise (resolve= > {/ *) all current form-item verifications * / let valid = true; / / default is via let count = 0 / / to match whether the current this.fields.forEach is fully checked (field = > {/ / each instance will have a validation check method field.validation (', error= > {/ / as long as there is a non-match, then the current check is the failed if (error) {valid = false). } / / if (+ + count = this.fields.length) {resolve (valid) is called only after all the form-item has been checked; / / the method uses then if (typeof callback = 'function') {callback (valid); / / directly calls the injected callback method});}) })}
5.form-item
Form-item is complicated. Let's talk about it one by one.
IsRequired to determine whether it is currently required.
ValidateState to determine the status of the current check
The current wrong value of validateMessage
Inject: ['form'] then we can call the events and values of the parent component through this.from.xxx
The fieldValue under computed may be constantly changing, so we use it by calculating properties.
The default value of initialValue is assigned when we are in mounted and currently need to check (sometimes in prop).
Mixins: [Emitter] Mixer is the method inside and date can be placed in the mixer if it is called frequently.
We form-item will pass two methods of input, blur and change (@ input used natively by input), to judge by the trigger in the check rules passed by form.
Form-item.vue {{label}} {{validateMessage}} import Emitter from'.. /.. / mixins/emitter'; import schema from 'async-validator' Export default {name: "aiFormItem", mixins: [Emitter], inject: ['form'], props: {label: {type: String, default:''}, prop: {type: String},}, computed: {fieldValue () {return this.form.model [this.prop] },}, data () {return {initialValue:', / / store the default value isRequired: false, / / whether there is a problem with the current validateState:'', / / verify whether validateMessage:'', / / verify the failed copy}} Methods: {/ * bind events for required verification * / setRules () {let that = this Let rules = this.getRules () / / the rule if (rules.length) {/ / every method that needs to be used after parent component filtering is used to check whether all elements of the array meet the specified condition (provided by the function) / / some returns true this.isRequired = rules.some as long as there is a match (rule= > {/ / if there is a required entry in the current verification rule, mark it as return rule.required })} / * blur event * / this.$on ('on-form-blur',that.onFieldBlur); / * change event * / this.$on (' on-form-change',that.onFieldChange)}, / * * obtain the verification rule of the current FormItem * / getRules () {let that = this from the rules attribute of FormItem Let rules = that.form.rules; rules = rules?rules [that.prop]: [] Return [] .concat (rules | | []) / / this way of writing allows the rule to be definitely in the form of an array}, / * Blur for form validation * / onFieldBlur () {this.validation ('blur')}, / * * change for form validation * / onFieldChange () {this.validation (' change')}, / * only blur and change are supported So filter out the rule rules that meet the requirements * / getFilteredRule (trigger) {let rules = this.getRules () / /! when res.trigger has no calling method, / / filter is checked by default to filter out the rule return rules.filter (res= >! res.trigger | | res.trigger.indexOf (trigger)! = =-1)}, / * * check data * @ param trigger check type * @ param callback callback function * / validation (trigger) Callback=function () {}) {/ / blur and change whether there are rules for the current way let rules = this.getFilteredRule (trigger) / / determine whether there is a rule if (! rules | | rules.length = 0) {return} / / set the status to verify the usage form of / / async-validator this.validateState = 'validating'; var validator = new schema ({[this.prop]: rules}) / / firstFields: true verifies only one validator.validate ({[this.prop]: this.fieldValue}, {firstFields: true}, (errors, fields) = > {this.validateState =! errors? 'success':' error'; this.validateMessage = errors? Errors [0] .message:'; callback (this.validateMessage);});}, / * clear the current form-item * / resetField () {this.form.model [this.prop] = this.initialValue }}, / / when component rendering, cache the instance in Form mounted () {/ / if no prop is passed, no verification is required, and there is no need to cache if (this.prop) {this.dispatch ('aiForm','on-form-item-add', this); / / set the initial value to restore the default value this.initialValue = this.fieldValue on reset / / add form this.setRules ()}}, / / remove beforeDestroy () {this.dispatch ('iForm',' on-form-item-remove', this);},} .ai-form-item-label-required:before {content:'*'; color: red;} .ai-form-item-message {color: red;} from the cache of Form before the component is destroyed.
5.input
Value supports one input parameter.
Because a parameter injected by input cannot be directly used in input, it is assigned to defaultValue first, and then watch is used to continuously assign values to defaultValue to achieve a modified binding of the parent component.
Import Emitter from'.. / mixins/emitter.js' export default {name: "aiInput", mixins: [Emitter], props: {value: {type: String, default:''}}, data () {return {defaultValue: this.value}}, watch: {value (val) {this.defaultValue = val }}, methods: {/ * change event * @ param event * / handleInput (event) {/ / current model assignment this.defaultValue = event.target.value; / / vue native method return out this.$emit ('input',event.target.value) / / send the current value to aiFormItem to verify this.dispatch ('aiFormItem','on-form-change',event.target.value)}, / * blur event * @ param event * / handleBlur (event) {/ / vue native method return out this.$emit (' blur',event.target.value) / / send the current value to aiFormItem to verify this.dispatch ('aiFormItem','on-form-blur',event.target.value)}
Last
Finally, the last one can be used at present.
Test import AiForm from ".. / components/form/form"; import AiFormItem from ".. / components/form/form-item"; import AiInput from ".. / components/input/ai-input" Export default {name: 'home', components: {AiInput, AiFormItem, AiForm},], data () {return {formValidate: {name:' 123zcodes, mail:''}, ruleValidate: {name: [{required: true, message: 'user name cannot be empty', trigger: 'blur'},],} Methods: {changeButton () {this.$refs.formItems.resetFields () / clear method this.$refs.formItems.validate () / / Verification method. Then (res= > {console.log (res)})}}, is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.