el-input是element ui中使用最頻繁的組件之一了,分析其構成從四個方面入手:DOM結構,屬性,樣式,事件入手
DOM結構:
<div> <input /> </div>
結構很簡單,這就相當於一個主干,剩下的樣式,事件,屬性都在這個基礎上擴充
屬性:
既然是封裝,input原生的屬性基本上都要覆蓋到,個人猜測element團隊是按照w3c官方資料來整理的,這樣絕對保證不遺漏,這種方式很值得借鑒,如下:
// 兼容文本框和文本域的情況 <template v-if="type !== 'textarea'"> // code.. </template> <textarea v-else> // code.. </textarea>
// 兼容了tabindex屬性,文本框,密碼框,是否禁用,是否自動完成,是否只讀,input,focus,blur,change事件 <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" @compositionend="handleCompositionEnd" @input="handleInput" @focus="handleFocus" @blur="handleBlur" @change="handleChange" :aria-label="label" >
這些屬性都通過父組件的props方式傳給子組件
樣式:
樣式控制比較簡單,根據props屬性,結合數組和對象方式,拼湊出符合實際要求的樣式組。從源碼可以看出樣式主要應用在input父元素div上以及前置元素和后置元素span上
// 根據type確定應用el-textarea還是el-input // 根據inputDisabled屬性確定是否啟用is-disabled屬性,其他類推 // 同時添加了鼠標移入移出時的hover樣式控制 <div :class="[ type === 'textarea' ? 'el-textarea' : 'el-input', inputSize ? 'el-input--' + inputSize : '', { 'is-disabled': inputDisabled, 'el-input-group': $slots.prepend || $slots.append, 'el-input-group--append': $slots.append, 'el-input-group--prepend': $slots.prepend, 'el-input--prefix': $slots.prefix || prefixIcon, 'el-input--suffix': $slots.suffix || suffixIcon || clearable || showPassword } ]" @mouseenter="hovering = true" @mouseleave="hovering = false" > // code... </div>
事件:
組件除提供focus,blur,change等常見事件外,還提供了很多可通過配置項啟用的事件,如:
clearable // 配置項,設置true后顯示叉號,點擊直接清除input框內容
總結:
el-input實現的功能還是挺多的,總體思路就按上面進行,盡可能通過各種配置項簡化使用,內部實現則是功能最小化,就知識層面來說沒什么難度,關鍵勝在結構嚴謹縝密,相信很多人都能看的懂,但要自己寫一個就沒那么容易了。