关于表单校验el-input作的主要工做就是跟el-form-item交互,把input的相关事件发送给el-form-item,上一篇已经讲到在el-form-item的mounted的生命周期里面有以下代码的javascript
this.$on('el.form.blur', this.onFieldBlur);
this.$on('el.form.change', this.onFieldChange);
复制代码
咱们在el-input里面依然能够看到inject,鉴于有不少单独使用el-input的地方,因此也给了默认值。html
inject: {
elForm: {
default: ''
},
elFormItem: {
default: ''
}
},
复制代码
其实这里面的比较简单,基本都是控制状态和样式的,有些状态是由el-form或者el-form-item控制的。java
直接监听父级传入的value,根据value来设置组件内保存的currentValue。element-ui
focus() {
(this.$refs.input || this.$refs.textarea).focus();
},
blur() {
(this.$refs.input || this.$refs.textarea).blur();
},
select() {
(this.$refs.input || this.$refs.textarea).select();
},
handleFocus(event) {
this.focused = true;
this.$emit('focus', event);
},
handleBlur(event) {
this.focused = false;
this.$emit('blur', event);
if (this.validateEvent) {
this.dispatch('ElFormItem', 'el.form.blur', [this.currentValue]);
}
},
handleInput(event) {
const value = event.target.value;
this.setCurrentValue(value);
if (this.isOnComposition) return;
this.$emit('input', value);
},
handleChange(event) {
this.$emit('change', event.target.value);
},
handleComposition(event) {
if (event.type === 'compositionend') {
this.isOnComposition = false;
this.currentValue = this.valueBeforeComposition;
this.valueBeforeComposition = null;
this.handleInput(event);
} else {
const text = event.target.value;
const lastCharacter = text[text.length - 1] || '';
this.isOnComposition = !isKorean(lastCharacter);
if (this.isOnComposition && event.type === 'compositionstart') {
this.valueBeforeComposition = text;
}
}
},
复制代码
属性validateEvent
默认是true
, 调用dispatch向上发送事件,若是存在父组件el-form-item的话,就能直接$emit对应的事件了。ui
在此,element-ui的表单校验系列就讲完了。this
顺便提一下compositionstart
,compositionupdate
,compositionend
事件。 以一个业务场景举例吧:spa
好比表单里还能够输入两个字符,但我输入中文用的是拼音,要完成最后两个汉字的输入,须要按不少个字母键,但每一键都会由于input事件而截取value,致使最后两个汉字不能输入。code
解决办法,使用composition来处理,有compositionstart和compositionend事件。orm
当咱们打汉字的时候,是属于非直接输入的,这个时候应当是咱们按下空格键或者选择某个汉字词后才算真正的输入,使用compositionend事件后取到的值来进行长度判断。htm
compositionstart事件在用户开始进行非直接输入的时候出触发,在非直接输入结束,也就是在用户点候选词或者点击选定按钮以后,会出发compositionend事件。
el-input处于compositionstart
或者compositionupdate
事件进行中会用了isOnComposition
来标记下,具体是根据最后一个字符来判断的this.isOnComposition = !isKorean(lastCharacter);
,若是是compositionstart
还会用valueBeforeComposition
先存储input里面输入的值。 原文地址:element-ui表单源码解析之el-input