function isValueNumber(value) {
return(/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9]*$)|(^-?0{1}$)/).test(value + '');
}
Vue.component('input-number',{
template: '\
<div class=input-number>\
<input\
type="text"\
:value="currentValue"\
@change="handleChange"\
@focus="keyControl">\
<button \
@click="handleDown" \
:disabled="currentValue<=min">-</button>\
<button \
@click="handleUp" \
:disabled="currentValue>=max">+</button>\
</div>',
data: function (){
return {
currentValue: this.value,
currentStep: this.$parent.step
}
},
watch: {
currentValue: function (val){
this.$emit('input',val);
this.$emit('on-change',val);
},
value: function(val){
this.updateValue(val);
}
},
methods: {
handleDown: function(){
if(this.currentValue<=this.min) return;
this.currentValue-=this.currentStep;
},
handleUp: function(){
if(this.currentValue>=this.max) return;
this.currentValue+=this.currentStep;
},
updateValue: function(val){
if(val>this.max) val=this.max;
if(val<this.min) val=this.min;
this.currentValue=val;
},
handleChange: function(event){
var val = event.target.value.trim();
var max = this.max;
var min = this.min;
if(isValueNumber(val)) {
val = Number(val);
this.currentValue = val;
if(val > max) {
this.current = max;
}
if(val < min) {
this.current = min;
}
} else {
//如果输入的不是数字,将输入的内容重置为之前的currentValue
event.target.value = this.currentValue;
}
},
keyControl: function(){
var _this=this;
$(window).keydown(function(e){
if($('input')){
if(e.keyCode==38){
_this.handleUp();
}
else if(e.keyCode==40){
_this.handleDown();
}
}
});
}
},
mounted: function(){
this.updateValue(this.value);
},
props:{
max:{
type: Number,
default: Infinity
},
min: {
type: Number,
default: -Infinity
},
value: {
type:Number,
default: 0
},
step: {
type:Number,
default: 1
}
}
})
|