一个简易的数字输入框组件

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

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

入口

<template>
  <input-number v-model="value" :max="10" :min="0"></input-number>
</template>
<script>
import InputNumber from './input.vue'
export default {
  data () {
    return {
      value: 5
    }
  },
  components: {
    InputNumber
  }
}
</script>

组件

<template>
<div class="input-nubmer">
  <input type="text"
    :value="currentValue"
    @change="handleChange"/>
    <button
      @click= "handleDown"
      :disabled="currentValue<= min"
      >-</button>
       <button
      @click= "handleUp"
      :disabled="currentValue>= max"
      >+</button>
</div>
</template>
<script>
export default {
//props属性
  props: {
    value: {
      type: Number,
      default: 0
    },
    max: {
      type: Number,
      default: Infinity
    },
    min: {
      type: Number,
      default: -Infinity
    }
  },
  data () {
    return {
      currentValue: this.value
    }
  },
  //监听属性value 和currentvalue
  watch: {
    currentValue (val) {
      this.$emit('input', val)
    },
    value (val) {
      this.updateValue(val)
    }
  },
  methods: {
  //输入值变化时候处理
    handleChange (event) {
      let val = event.target.value.trim()
      let max = this.max
      let min = this.min
      val = Number(val)
      this.currentValue = val
      if (val > max) {
        this.currentValue = max
      } else if (val < min) {
        this.currentValue = min
      }
    },
    handleDown () {
      if (this.currentValue <= this.min) {
        return false
      }
      this.currentValue -= 1
    },
    handleUp () {
      if (this.currentValue >= this.max) {
        return false
      }
      this.currentValue += 1
    },
    updateValue (val) {
      if (val > this.max) {
        val = this.max
      }
      if (val < this.min) {
        val = this.min
      }
      this.currentValue = val
    }
  },
  mounted () {
  //初始化值过滤
    this.updateValue(this.value)
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/yilanyoumeng3/article/details/82383804