系列文章目录
第一章 element源码(一)简要介绍
第二章 element源码(二)Layout 布局组件
第三章 element源码(三)色彩、字体、边框与图标
第四章 element源码(四)button按钮组件
第五章 element源码(五)radio 单选框组件
第六章 element源码(六)check 多选框框组件
第七章 element源码(七)input 输入框组件
一、input组件
<div @mouseenter="hovering = true"
@mouseleave="hovering = false">
<template v-if="type !== 'textarea'">
</template>
<textarea v-else>
</textarea>
<span v-if="isWordLimitVisible && type === 'textarea'"
class="el-input__count">{{ textLength }}/{{ upperLimit }}</span>
</div>
结构:最外层div实现鼠标移入,移出状态管理;然后input和textarea的判断;字数计数器
二、逻辑实现
value / v-model 绑定值 string / number
这个地方我本以为会很简单就像单选框/复选框一样,计算属性中get取值set传值。但是涉及到中文输入的交互优化,下面我会详细介绍
<input
ref="input"
@compositionstart="handleCompositionStart"
@compositionupdate="handleCompositionUpdate"
@compositionend="handleCompositionEnd"
@input="handleInput">
@input触发输入事件获取值,event.target.value拿到值。然后是做两个处理1,向父组件传递新值value;2,计算属性value触发子组件显示的值赋值(字符串类型)
handleInput (event) {
if (this.isComposing) return;
if (event.target.value === this.nativeInputValue) return;
this.$emit('input', event.target.value);
this.$nextTick(this.setNativeInputValue);
}
// this.$refs.input.value = this.nativeInputValue
setNativeInputValue () {
const input = this.getInput();// return this.$refs.input || this.$refs.textarea;
if (!input) return;
if (input.value === this.nativeInputValue) return;//return this.value === null || this.value === undefined ? '' : String(this.value);
input.value = this.nativeInputValue;
},
到这里可能会疑惑这样做意义在哪,用单选框的方式好像更简便,这种简便写法,如下
// 父组件
<el-input v-model="input" placeholder="请输入内容"></el-input>
// 子组件
<input v-modle="value"></input>
props:{
value:"",
},
computer:{
value:{
get(){
return this.value
},
set(val){
this.$emit('input',val)
}
}
}
之所以这么复杂和compositionstart,compositionupdate和compositionend三个事件有关,简单说一下要达到效果就是在打字时候输入法中的英文不记录最后的汉字才做记录,详细可以看这篇文章 你知道compositionstart和compositionend吗
三、属性
clearable 是否可清空 boolean
<div @mouseenter="hovering = true"
@mouseleave="hovering = false">
<input @focus="handleFocus"></input>
</div>
computed: {
showClear() {
return this.clearable &&
!this.inputDisabled &&
!this.readonly &&
this.nativeInputValue &&
(this.focused || this.hovering);
},
}
methods:{
clear() {
this.$emit('input', '');
this.$emit('change', '');
this.$emit('clear');
},
}
计算属性管理showClear显示清空按钮的状态,clearable(设置可清空) inputDisabled(没有禁用) readonly (不是只读) nativeInputValue(有值存在) foucused||hovering(聚焦或者鼠标移入)
实现逻辑直接清空就行了简单粗暴