vue中设置input输入框的值为正整数,不能为负数和小数

一、新建文件夹

 

 二、int.js中新增自定义指令

 

 代码如下:

import Vue from 'vue'
Vue.directive('Int', {
  bind: function (el) {
    const input = el.getElementsByTagName('input')[0]
    input.onkeyup = function (e) {
      if (input.value.length === 1) {
        input.value = input.value.replace(/[^0-9]/g, '')
      } else {
        input.value = input.value.replace(/[^\d]/g, '')
      }
      trigger(input, 'input')
    }
    input.onblur = function (e) {
      if (input.value.length === 1) {
        input.value = input.value.replace(/[^0-9]/g, '')
      } else {
        input.value = input.value.replace(/[^\d]/g, '')
      }
      trigger(input, 'input')
    }
  }
})
const trigger = (el, type) => {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}
三、在main.js中引入自定义指令的文件

 

 四、在组件中使用自定义指令

 

 完。。。。。。。。。。

posted on 2021-04-30 15:30  被窝暖暖嘻嘻嘻  阅读(2599)  评论(0编辑  收藏  举报

导航