javascript - 在 Vue 中实现 @keypress

标签 javascript vue.js vuejs2 vue-component onkeypress

我正在尝试在 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/

相关文章:

javascript - Google OAuth token 过期

javascript - Jquery 添加椭圆 (...) 并根据高度而非宽度 chop 文本

javascript - Pyodide 无法将 xlsx 文件读入 pandas

vue.js - 如何阻止 <router-link> 将用户发送到另一个页面?

javascript - 表格中的 vue 可拖动宽度有问题吗?

javascript - 如何检查特定元素的 DOM 并创建新的 Vue 实例?

javascript - 全局变量和 JavaScript 中的 'window.variable' 有什么区别?

javascript - 添加组织的工作时间

javascript - vuejs中如何获取data-*属性的值

javascript - 我通过运行 npm run build 构建了我的 Vuejs 应用程序,打开 index.html 抛出错误: 无法加载资源:net::ERR_FILE_NOT_FOUND