Vue 数字输入组件
by deniro
HTML
<div id="app">
<number-input v-model="value" :min="0" :max="50" :step="5"></number-input>
</div>
Vue
/**
* 是否为数字
* @param val
* @returns {boolean}
*/
function isNum(val) {
return (/^[0-9]*$/).test(val);
}
/**
* 数字输入组件
*/
Vue.component('number-input', {
template: '\
<div class="number-input">\
<input \
type="text"\
:value="currentVal"\
@change="change"\
@keyup.up="up"\
@keyup.down="down">\
<button\
@click="down"\
:disabled="currentVal<=min">-</button>\
<button\
@click="up"\
:disabled="currentVal >=max">+</button>\
</div>',
props: {//校验
//最大值
max: {
type: Number,
default: Infinity
},
//最小值
min: {
type: Number,
default: -Infinity
},
//初始值
value: {
type: Number,
default: 0
},
//步伐
step: {
type: Number,
default: 1
}
},
data: function () {
return {
currentVal: this.value
}
},
watch: {
currentVal: function (val) {
console.log("currentVal:" + this.currentVal);
this.$emit('input', val);
},
value: function (val) {//更新 currentVal
this.update(val);
}
},
methods: {
test: function () {
console.log("test");
},
/**
* 更新
* @param val
*/
update: function (val) {
//让输入的值在限定范围内
if (val > this.max) {
val = this.max;
}
if (val < this.min) {
val = this.min
}
this.currentVal = val;
},
/**
* 减少
*/
down: function () {
if (this.currentVal <= this.min) {
return;
}
this.currentVal -= this.step;
},
/**
* 增长
*/
up: function...