Vue数字输入框组件使用方法详解

2020-06-16 06:56:26易采站长站整理

当父组件value发生变化时,子组件currentValue也跟着变化。
当子组件currentValue变化时,使用$emit触发v-model,使得父组件value也跟着变化


watch: {
// 监听属性currentValue与value
currentValue(val) {
// currentValue变化时,通知父组件的value也变化
this.$emit('input', val);

},
value(val) {
// 父组件value改变时,子组件currentValue也改变
this.updataValue(val);
}
},
methods: {
updataValue(val) {
if(val > this.max) val = this.max;
if(val < this.min) val = this.min;
this.currentValue = val;
}
},
// 第一次初始化时,也对value进行过滤
mounted: function() {
this.updataValue(this.value);
}

上述代码中,生命周期mounted钩子也使用了updateValue()方法,是因为初始化时也要对value进行验证。

父子间的通信解决差不多了,接下来完成按钮的操作:添加handleDown与handleUp方法


template: `
<div class="input-number">
<input type="text" :value="currentValue" />
<button @click="handleDown" :disabled="currentValue <= min">-</button>
<button @click="handleUp" :disabled="currentValue >= max">+</button>
</div>
`,
methods: {
updataValue(val) {
if(val > this.max) val = this.max;
if(val < this.min) val = this.min;
this.currentValue = val;
},
// 点击减号 减10
handleDown() {
if(this.currentValue < this.min) return
this.currentValue -= this.prop_step;
},
// 点击加号 加10
handleUp() {
if(this.currentValue < this.min) return
this.currentValue += this.prop_step;
},

当用户在输入框想输入具体的值时,怎么办?

为input绑定原生change事件,并且判断输入的是否数字:


<input type="text" :value="currentValue" @change="handleChange" />

在methods选项中,添加handleChange方法:


// 输入框输入值
handleChange(event) {
var val = event.target.value.trim();
var max = this.max;
var min = this.min;
if(isValueNumber(val)) {
val = Number(val);
if(val > max) {
this.currentValue = max;
}
if(val < min) {
this.currentValue = min;
}
this.currentValue = val;
console.log(this.value);
}else {
event.target.value = this.currentValue;
}

在外层添加判断是否为数字的方法isValueNumber:


function isValueNumber(value) {
return (/(^-?[0-9]+.{1}d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/).test(value+ '');