如何使用 VueJS 防止数字输入 [英] How can I prevent numeric inputs using VueJS
问题描述
我需要创建一个验证,以防止用户在文本框中输入数字输入.我找到了一些使用原生 javascript 的解决方案,但它在我这边不起作用.
I need to create a validation that prevent the user from inputting numeric inputs on a textbox. I found some solution using a native javascript but it is not working on my side.
在我的文本框中,我有这个触发器
On my text box I have this trigger
v-on:keyup="preventNumericInput($event)">
在我的 Vue 上,我在我的类上创建了一个函数
And on my Vue I created a function on my class
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();
}
}
你能帮我解决这个问题吗?
Can you help me with this?
推荐答案
正如我在评论中提到的,keyup
将触发太晚以防止将值输入到输入字段中.例如,考虑按住某个键重复输入相同的值;没有键向上.
As mentioned in my comment, keyup
will be firing too late to prevent the value being entered into the input field. For example, think about holding a key down to enter the same value repeatedly; there is no key up.
改为使用keydown
或keypress
<input @keypress="preventNumericInput">
演示 ~ http://jsfiddle.net/wadt08jm/1/
这篇关于如何使用 VueJS 防止数字输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!