vue自定义指令:v-only-number指令限制只能输入数字

836 阅读1分钟

一、效果

动画.gif

二、指令封装

/**
 * 使用 v-only-number.positive.fill="3"
 * 
 *    ="3" 表示允许输入小数,小数位数最多3位,默认为0
 *    positive 表示只能输入0和正数
 *    fill 表示自动补零。前提是允许输入小数,否则不要写fill修饰符
 * 
 */

Vue.directive('only-number', {
  bind: function (el, {
    value = 0,
    modifiers
  }) {
    el = el.nodeName == "INPUT" ? el : el.children[0]
    const RegStr = value == 0 ? `^[\\+\\-]?\\d+\\d{0,0}` : `^[\\+\\-]?\\d+\\.?\\d{0,${value}}`;
    el.addEventListener('keyup', function () {
      if (el.value != '-') {
        el.value = el.value.match(new RegExp(RegStr, 'g'));
        if (modifiers.positive) {
          el.value = el.value.replace('-', '')
        }
        el.dispatchEvent(new Event('input'))
      }
    })
    el.addEventListener('blur', function () {
      let num = el.value.match(new RegExp(RegStr, 'g')) || '0.00';
      // 自动补零
      if (modifiers.fill) {
        let str = num.toString()
        let decimalPosition = str.indexOf('.')
        if (decimalPosition < 0) {
          decimalPosition = str.length
          str += '.'
        }
        while (str.length <= (decimalPosition + Number(value))) {
          str += '0'
        }
        num = str
        el.value = num
      }
      if (modifiers.positive) {
        el.value = el.value.replace('-', '')
      }
      el.dispatchEvent(new Event('input'))
    })
  }
})

三、使用

<el-input v-model="inputValue" v-only-number.fill.positive="3" clearable></el-input>