【问题标题】:How can I prevent numeric inputs using VueJS如何使用 VueJS 防止数字输入
【发布时间】:2022-04-06 19:56:44
【问题描述】:

我需要创建一个验证来阻止用户在文本框中输入数字输入。我找到了一些使用原生 javascript 的解决方案,但它不适用于我。

在我的文本框中我有这个触发器

v-on:keyup="preventNumericInput($event)"> 

在我的 Vue 上,我在课堂上创建了一个函数

preventNumericInput($event) {
    console.log($event.keyCode); //will display the keyCode value
    console.log($event.key); //will show the key value

    var keyCode = ($event.keyCode ? $event.keyCode : $event.which);
    if (keyCode > 47 && keyCode < 58) {
        $event.preventDefault();
    }
}

你能帮我解决这个问题吗?

【问题讨论】:

标签: javascript vue.js vuejs2


【解决方案1】:

正如我在评论中提到的,keyup 触发太晚,无法阻止将值输入到输入字段中。例如,考虑按住一个键重复输入相同的值;没有键向上。

改为使用keydown 或keypress

<input @keypress="preventNumericInput">

演示~http://jsfiddle.net/wadt08jm/1/

【讨论】:

    【解决方案2】:
    • 输入必须是类型号,否则isNaN无效

         <input type="number" :value="price" step="0.1" min="0" @input="onInput($event)" >
      
    • 将','替换为'.'

    • 如果不是数字则测试

    • 如果不是数字,则用 element.value 替换可观察到的价格

      data () {
        return { price: 0 }
      },
      methods: {
        onInput (e: Event) {
          const element = e.target as HTMLInputElement
          const value = parseFloat(element.value === '' ? '0' : element.value.replace(',', '.'))
          if (isNaN(value)) {
            element.value = this.price.toString()
          } else {
            this.price = value
          }
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      相关资源
      最近更新 更多