输入框只能输入数字

export function validateNumber(str) {
  return str.replace(/[^\d]/g, '')
}
export function validateNumber(str) {
  return str.replace(/[^\d]/g, '')
}

import { getLength, validateNumber } from '@/utils/validate'

methods:{
   onlyNumber(val) {
      return validateNumber(val)
    },
}

 <el-input
              v-model="form.fieldMaxLength"
              @input="form.fieldMaxLength = onlyNumber(form.fieldMaxLength)"
              placeholder="请填写字符串最大长度"
              maxlength="50"
              oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
            ></el-input>

//指令的形式

function onInput(el, ele, binding, vnode) {
 function handle() {
 // 只保留数字
 ele.value = ele.value.replace(/[^\d]/g, '')
 } 

 return handle
}
const numberInput= {
 bind(el, binding, vnode) {
 const ele = el.tagName === 'INPUT' ? el : el.querySelector('input')
 ele.addEventListener('input', onInput(el, ele, binding, vnode), false)
 },
}
Vue.directive('number-input', numberInput)

<el-input v-model="model" v-number-input />


function handle() {
+ let val = ele.value
+ // modifiers为修饰符对象,传入了float,则其float属性为true
+ if (binding.modifiers.float) {
+ // 清除"数字"和"."以外的字符
+ val = val.replace(/[^\d.]/g, '')
+ // 只保留第一个, 清除多余的
+ val = val.replace(/\.{2,}/g, '.')
+ // 第一个字符如果是.号,则补充前缀0
+ val = val.replace(/^\./g, '0.')
+ } else {
 val = ele.value.replace(/[^\d]/g, '')
 }
 ele.value = val
}
来源:https://www.jb51.net/article/169052.htm