VUE常用自定义指令

172 阅读1分钟

只能输入金额(不包括 - 号,最多两位小数)

Vue.directive('enterMoney', {  inserted: function (el) {    el.addEventListener('keypress', function (e) {      e = e || window.event      const charcode = typeof e.charCode === 'number' ? e.charCode : e.keyCode      const re = /\d/      if (el.children[0].value && el.children[0].value.includes('.')) {        let oldLen = el.children[0].value.substr(0, el.children[0].value.indexOf('.'))        if (el.children[0].value.length === oldLen.length + 3) {          e.preventDefault()        }      }      if (charcode === 46) {        if (el.children[0].value.includes('.') || !el.children[0].value) {          e.preventDefault()        }        return      } else if (!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey) {        if (e.preventDefault) {          e.preventDefault()        } else {          e.returnValue = false        }      }    })  }})

<el-input v-enter-money placeholder="请输入金额"></el-input>