前言:我们都知道vue中v-model
指令可以实现双向数据绑定,但他本质是一个语法糖,比如组件上的v-model
默认会利用名为value
的 prop 和名为input
的事件。在自定义实现的过程中,发现在使用输入法时,输入拼音选择候选词同样会触发原生input标签
的input事件
,从而更新value
。但element-ui的input组件
便不会如此,其实就是用到了composition events
。
compositionend事件
当文本段落的组成完成或取消时, compositionend 事件将被触发 (具有特殊字符的触发, 需要一系列键和其他输入, 如语音识别或移动中的字词建议)。
compositionstart事件
触发于一段文字的输入之前(类似于keydown
事件,但是该事件仅在若干可见字符的输入之前,而这些可见字符的输入可能需要一连串的键盘操作、语音识别或者点击输入法的备选词)。
compositionupdate
事件触发于字符被输入到一段文字的时候(这些可见字符的输入可能需要一连串的键盘操作、语音识别或者点击输入法的备选词)
(内容来自MDN)
<input
:tabindex="tabindex"
v-if="type !== 'textarea'"
class="el-input__inner"
v-bind="$attrs"
:type="showPassword ? (passwordVisible ? 'text': 'password') : type"
:disabled="inputDisabled"
:readonly="readonly"
:autocomplete="autoComplete || autocomplete"
ref="input"
@compositionstart="handleCompositionStart"
@compositionupdate="handleCompositionUpdate"
@compositionend="handleCompositionEnd"
@input="handleInput"
@focus="handleFocus"
@blur="handleBlur"
@change="handleChange"
:aria-label="label"
\>
// 方法
handleCompositionStart() {
this.isComposing = true;
},
handleCompositionUpdate(event) {
const text = event.target.value;
const lastCharacter = text[text.length - 1] || '';
// 此处通过正则对最后一个字符是否韩文作一个判断,有懂韩文的请指教一下~
this.isComposing = !isKorean(lastCharacter);
},
handleCompositionEnd(event) {
if (this.isComposing) {
this.isComposing = false;
this.handleInput(event);
}
},
handleInput(event) {
// should not emit input during composition
if (this.isComposing) return;
// hack for https://github.com/ElemeFE/element/issues/8548
// should remove the following line when we don't support IE
if (event.target.value === this.nativeInputValue) return;
this.$emit('input', event.target.value);
// ensure native input value is controlled
// see: https://github.com/ElemeFE/element/issues/12850
this.$nextTick(this.setNativeInputValue);
},
handleChange(event) {
this.$emit('change', event.target.value);
},
可以看到,原生的input绑定了许多事件,其中input事件
中,先判断isComposing
的布尔值,看是否触发了composition events
的一系列方法,然后才决定是否执行下段代码this.$emit('input', event.target.value)
。
@compositionstart="handleCompositionStart"
@compositionupdate="handleCompositionUpdate"
@compositionend="handleCompositionEnd"
@input="handleInput"`
总结:此事件本身较为简单,下分只有三个状态的事件,但是在双向数据绑定的实现中,又是比较重要的一环,避免在输入法选词时连续触发。看源码一时爽;一直看源码一直爽
。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。