前言:咱们都知道vue中v-model
指令能够实现双向数据绑定,但他本质是一个语法糖,好比组件上的v-model
默认会利用名为value
的 prop 和名为input
的事件。在自定义实现的过程当中,发如今使用输入法时,输入拼音选择候选词一样会触发原生input标签
的input事件
,从而更新value
。但element-ui的input组件
便不会如此,其实就是用到了composition events
。vue
compositionend事件
当文本段落的组成完成或取消时, compositionend 事件将被触发 (具备特殊字符的触发, 须要一系列键和其余输入, 如语音识别或移动中的字词建议)。git
compositionstart事件
触发于一段文字的输入以前(相似于keydown
事件,可是该事件仅在若干可见字符的输入以前,而这些可见字符的输入可能须要一连串的键盘操做、语音识别或者点击输入法的备选词)。github
compositionupdate
事件触发于字符被输入到一段文字的时候(这些可见字符的输入可能须要一连串的键盘操做、语音识别或者点击输入法的备选词)
(内容来自MDN)element-ui
<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)
。ui
@compositionstart="handleCompositionStart" @compositionupdate="handleCompositionUpdate" @compositionend="handleCompositionEnd" @input="handleInput"`
总结:此事件自己较为简单,下分只有三个状态的事件,可是在双向数据绑定的实现中,又是比较重要的一环,避免在输入法选词时连续触发。看源码一时爽;一直看源码一直爽
。this