我正在尝试在 Vue 组件中实现 onkeypress
事件。在按键时,我想限制除数字之外的所有按键代码。我正在尝试以下操作。
使用 onkeypress 事件,一切正常!
<input type="number" onkeypress="return (event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode)));" />
当我将上面的内容转换为在Vue中使用时,它不起作用! :(
<input type="number" @keypress="restrictChars($event)" />
<script>
export default {
name: 'quantity-selector',
methods: {
restrictChars: function($event) {
return ($event.charCode === 0 || /\d/.test(String.fromCharCode($event.charCode)));
}
}
我错过了什么?我不明白出了什么问题?非常感谢任何帮助!
最佳答案
问题解决了。虽然我在读取 keyCode 时返回了一个 bool 值,但我并没有阻止默认的按键操作。 restrictChars
方法应该如下所示!
restrictChars: function($event) {
if ($event.charCode === 0 || /\d/.test(String.fromCharCode($event.charCode))) {
return true
} else {
$event.preventDefault();
}
}
关于javascript - 在 Vue 中实现 @keypress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53346820/