<template>
  <input type="tel"
         class="number-input icon"
         :class="icon===''?'':'icon--'+icon"
         :value="iptNum"
         @input="change"
         @change="change" />
</template>

<script>
export default {
  name: 'NumberInput',
  model: {
    prop: 'value',
    event: 'my-change'
  },
  props: {
    icon: {
      type: String,
      default: 'pen'
    },
    value: {
      type: [String, Number]
    }
  },

  data() {
    return {
      oldNum: ''
    };
  },
  computed: {
    iptNum() {
      const t = ('' + this.oldNum).trim();
      if (t === '') {
        this.$emit('my-change', t);
      } else {
        this.$emit('my-change', +this.oldNum);
      }
      return t;
    }
  },
  watch: {
    value: {
      handler(val, oldVal) {
        if (!isNaN(val) && val !== null) {
          this.oldNum = val;
        }
      },
      immediate: true
    }

  },
  mounted() {

  },
  methods: {
    change(event) {
      const val = event.target.value;
      // 只能是正整数或空,可根据需求修改正则
      if (/^[0-9]\d*$|^$/.test(val)) {
        this.oldNum = val;
      } else {
        event.target.value = this.oldNum;
      }
    }
  }
};
</script>
