Vue 数字输入框组件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xukongjing1/article/details/86441131

输入框只能输入数字,并且有两个快捷按钮,可以直接加1或减1。除此之外,还可以额设置初始值、最大值、最小值、步长,在数值改变时,触发一个自定义事件来通知父组件。 

在父组件中使用

<template>
  <div>
    <number-box v-model="value" :max="50" :min="0" :step="2"></number-box>
  </div>  
</template>
<script>
import NumberBox from './subComponents/NumberBox'
export default {
  data(){
    return {
      value: 5,
    }
  },
  components:{
    NumberBox
  }
}
</script>
<style scoped>

</style>

组件 NumberBox.vue源码

<template>
  <div class="input-number">
    <button @click="handleDown" :disabled="currentValue <= min" >-</button>
    <input type="text" :value="currentValue" @change="handleChange" @keyup.up='handleUp' @keyup.down='handleDown'> 
    <button @click="handleUp" :disabled="currentValue >= max">+</button>
  </div>
</template>
<script>
export default {
  data(){
    return{
      currentValue: this.value
    }
  },
  props:{
    max: {type: Number, default: Infinity},
    min: {type: Number, default: -Infinity},
    value: {type: Number, default: 0},
    step: {type: Number, default:1},
  },
  methods:{
    handleDown(){
      if(this.currentValue <= this.min) return;
      this.currentValue -= this.step;
    },
    handleUp(){
      if(this.currentValue >= this.max) return;
      this.currentValue += this.step;
    },
    handleChange(){
      let val = event.target.value.trim();
      let max = this.max;
      let min = this.min;
      if(this.isValueNumber(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;
      }
    },
    updateValue(val){
      if(val > this.max) val = this.max;
      if(val < this.min) val = this.min;
      this.currentValue = val;
    },
    isValueNumber(value){
      return (/(^-?[0-9]+\.{1}\d+$) | (^-?[1-9][0-9]*$) | (^-?0{1}$)/).test(value + '');
    }
  },
  mounted(){
    this.updateValue(this.value);
  },
  watch:{
    currentValue(val){
      this.$emit('input', val);
      this.$emit('on-change', val);
    },
    value(val){
      this.updateValue(val);
    }
  }
}
</script>
<style scoped>

</style>


猜你喜欢

转载自blog.csdn.net/xukongjing1/article/details/86441131
今日推荐