zoukankan      html  css  js  c++  java
  • Vue指令限制输入框输入整数小数

    指令封装

    /**
       * 默认只可输入正整数
       * 修饰符float可输入小数,默认两位小数,若想n位小数,可v-input-number.float="n"
       * 修饰符negative可输入负数
       * */
      const inputNumber = {
        bind(el, binding, vNode) {
          let elem = el.tagName === 'INPUT' ? el : el.querySelector('input')
    
          elem.addEventListener('input', onInput(elem, binding, vNode), false)
        }
      }
    
      function onInput(elem, binding, vNode) {
        return () => {
          let val = elem.value
    
          // 只保留负号数字和小数点
          val = val.replace(/[^-d.]/g, '')
    
          // 根据negative修饰符选择是否保留负号
          if (binding.modifiers.negative) {
            val = val.replace(/(?!^)-/g, '')
          } else {
            val = val.replace(/-/g, '')
          }
    
          if (binding.modifiers.float) {
    
            // 只保留一个小数点
            let index = val.indexOf('.')
    
            if (index !== -1 && index !== val.length - 1) {
              val = val.substring(0, index) + '.' + val.substring(index + 1).replace(/./g, '')
            }
    
            // 限制小数位数,默认保留两位小数
            let pointKeep = isNaN(binding.value) ? 2 : parseInt(binding.value),
              reg = new RegExp('^(-?)(\d+)\.(\d{' + pointKeep + '}).*$')
    
            val = val.replace(reg, '$1$2.$3')
          } else {
            val = val.replace(/./g, '')
          }
    
          elem.value = val
          dispatchEvent(new Event('input'))
        }
      }
    
      Vue.directive('input-number', inputNumber)
    
    

    调用

    <input type="text" v-model="number" v-input-number.float.negative="3">
    

    在element-ui中el-input,使用dispatchEvent(new Event('input'))触发v-model值改变会有问题
    改用vNode.data.model.callback(val)来修改v-model的值
     elem.value = val
     vNode.data.model.callback(val)
    


    资料

    vue限制文本框输入数字的正确姿势

  • 相关阅读:
    C# 使用SMTP发送附件
    C# 获取文件名及扩展名
    邮件添加附件
    WPF 加载GIF动画
    IIS端口被占用 转载
    ReDim Preserve 的用途
    c# 构造函数执行顺序
    WriteLog
    SMS发送短信设置HttpWebRequest
    Directory.GetFiles
  • 原文地址:https://www.cnblogs.com/Grani/p/14122510.html
Copyright © 2011-2022 走看看