<!-- 数字input框 -->
<template>
  <el-input v-model="inputVal" :maxlength="maxLen" :disabled="disabled" :placeholder="placeholder" @input="handleInput" />
</template>

<script>
/**
 * 如果数字是负数必须在组件声明处标志isPositive此prop
 * eg:  <cy-number-input v-model="testVal" :is-positive="false" />
 *  <cy-number-input v-model="testVal" />
 */
export default {
  props: {
    maxLen: {
      type: Number,
      default: 255
    },
    placeholder: {
      type: String,
      default: '请输入身份证'
    },
    // 是否为正数
    isPositive: {
      type: Boolean,
      default: true
    },
    value: {
      type: [String, Number],
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      inputVal: ''
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val === undefined) return
        this.handleInput(String(val))
      },
      immediate: true
    },
    inputVal(val) {
      this.handleInput(val)
    }
  },
  methods: {
    handleInput(val) {
      // 移除非数字字符
      this.inputVal = val.replace(/[^\d]/g, '')
      if (!this.isPositive) {
        this.$emit('input', Number('-' + this.inputVal))
      } else {
        this.$emit('input', Number(this.inputVal))
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
