系列文章目录
第一章 element源码(一)简要介绍
第二章 element源码(二)Layout 布局组件
第三章 element源码(三)色彩、字体、边框与图标
第四章 element源码(四)button按钮组件
第五章 element源码(五)radio 单选框组件
第六章 element源码(六)check 多选框框组件
第七章 element源码(七)input 输入框组件
第八章 element源码(八)input-number 计数器组件
文章目录
一、input-number组件
<template>
<div @dragstart.prevent>
<span class="el-input-number__decrease" >
<i :class="`el-icon-${controlsAtRight ? 'arrow-down' : 'minus'}`"></i>
</span>
<span class="el-input-number__increase" >
<i :class="`el-icon-${controlsAtRight ? 'arrow-up' : 'plus'}`"></i>
</span>
<el-input >
</el-input>
</div>
</template>
input和两个span加减控件
二、逻辑实现
<el-input :value="displayValue">
</el-input>
data() {
return {
currentValue: 0,
userInput: null
};
},
watch: {
value: {
immediate: true,
handler(value) {
let newVal = value === undefined ? value : Number(value);
if (newVal !== undefined) {
if (isNaN(newVal)) {
return;
}
}
this.currentValue = newVal;
this.userInput = null;
this.$emit('input', newVal);
}
}
},
displayValue() {
if (this.userInput !== null) {
return this.userInput;
}
Value; return this.currentValue;
}
两个值:
userInput
用户输入,
currentValue
当前值
currentValue:(1)从父组件接收value时赋值currentValue;(2)加减控件修改currentValue
userInput:输入框输入值时给userInput赋值
input上绑定value的值
diplayValue
优先取
userInput
,为null时取
currentValue
increase() {
if (this.inputNumberDisabled || this.maxDisabled) return;
const value = this.value || 0;
const newVal = this._increase(value, this.step);
this.setCurrentValue(newVal);
},
decrease() {
if (this.inputNumberDisabled || this.minDisabled) return;
const value = this.value || 0;
const newVal = this._decrease(value, this.step);
this.setCurrentValue(newVal);
},
handleInput(value) {
this.userInput = value;
},
简单理解三个函数,前两个加减后赋值给currentValue,handleInput输入后赋值给userInput
<template>
<div @dragstart.prevent>
<span class="el-input-number__decrease"
v-repeat-click="decrease"
@keydown.enter="decrease">
<i :class="`el-icon-${controlsAtRight ? 'arrow-down' : 'minus'}`"></i>
</span>
<span class="el-input-number__increase"
v-repeat-click="increase"
@keydown.enter="increase">
<i :class="`el-icon-${controlsAtRight ? 'arrow-up' : 'plus'}`"></i>
</span>
<el-input
@input="handleInput"
@keydown.up.native.prevent="increase"
@keydown.down.native.prevent="decrease">
</el-input>
</div>
</template>
再看一下三个函数分别在什么事件下触发的,加减函数在点击控件时和键盘上下键按下时,输入时触发handleInput.
这里用了一个自定义指令v-repeat-click,这个在项目中也可以借鉴的,是用来做按钮防抖的
bind(el, binding, vnode) {
let interval = null;
let startTime;
const handler = () => vnode.context[binding.expression].apply();
const clear = () => {
if (Date.now() - startTime < 100) {
handler();
}
clearInterval(interval);
interval = null;
};
on(el, 'mousedown', (e) => {
if (e.button !== 0) return;
startTime = Date.now();
once(document, 'mouseup', clear);
clearInterval(interval);
interval = setInterval(handler, 100);
});
}