vue数字输入框组件

2,440 阅读1分钟

要求:

1.只能输入数字

2.两个快捷按钮可以加一或减一

3.可以设置初始值,最大值,最小值,每次增减步数

4.数值改变时通知父组件

5.聚焦时支持上下键增减

//input-number.vue
<template>
  <div class="input-number">
    <input type="text" :value="currentValue" @change="handleChange" @keyup.down="handleDown" @keyup.up="handleUp">
    <button @click="handleDown" :disabled="currentValue<=min">-</button>
    <button @click="handleUp" :disabled="currentValue>=max">+</button>
  </div>
</template>
<script>
  export default {
    props: {
      max: {
        type:Number,
        default:Infinity
      },
      min: {
        type:Number,
        default:-Infinity
      },
      value: {
        type: Number,
        default:0
      },
      step: {
        type: Number,
        default:1
      }
    },
    data: function () {
      return {
        currentValue:this.value
      }
    },
    watch:{
      currentValue:function (val) {
        this.$emit('input',val);
      },
      value:function (val) {
        this.updateValue(val)
      }
    },
    methods:{
      handleDown:function () {
        if(this.currentValue<=this.min) return;
        this.currentValue-=this.step;
      },
      handleUp:function () {
        if(this.currentValue>=this.max) return;
        this.currentValue+=this.step;
      },
      updateValue:function (val) {
        if(val>this.max) val=this.max;
        if(val<this.min) val = this.min;
        this.currentValue = val;
      },
      handleChange:function (event) {
        let val = event.target.value.trim();
        let max = this.max;
        let min = this.min;
        if(!isNaN(-val)){
          val = Number(val);
          this.currentValue = val;
          if(val>max){
            this.currentValue=max;
          }else if(val<min) {
            this.currentValue=min;
          }
        }else {
          event.target.value = this.currentValue
        }
      }
    },
    mounted:function () {
      this.updateValue(this.value)
    }
  }
</script>

使用:

<template>
  <div>
    <input-number v-model="value" :max="100" :min="-100" :step="10"></input-number>
  </div>
</template>
<script>
export default{
    data(){
      return {
        value:5
      }
    },
}
</script>