使用Vue.js从文本输入中按Enter键时阻止表单提交

使用Vue.js从文本输入中按Enter键时阻止表单提交

问题描述:

我在我的应用中使用Vue.js并在表单中输入文本

I am using Vue.js in my app and have a text input within a form

<div id="myVueForm">
<form>
   <input type="text"  v-on="keyup:addCategory | key 'enter'">

   <!-- more form fields -->
   <button type="submit">Submit Form</button>
</form>
</div>

在我的Vue实例中,我有以下

In my Vue instance I have the following

new Vue({
    el: '#myVueForm',

    methods: {
        addCategory: function(e)
        {
           if(e) e.preventDefault();
           console.log("Added a new category, thanks!");
        }
    }
});

尽管 preventDefault(); 调用,当用户在文本输入时按Enter键时,表单仍然提交(尽管 addCategory()方法会触发)。这种行为可以在这个小提琴中得到证明。

Despite the preventDefault(); call, when a user presses enter whilst on the text input the form still submits (although the addCategory() method does fire). This behaviour can be demonstrated in this fiddle.

我知道我可以使用jQuery来捕获事件并阻止提交,但我想看看Vue中是否可以这样做,因为它似乎是一种常见的用法。

I know I can use jQuery to catch the event and prevent the submit, but I'd like to see if it's possible in Vue to do this as it seems quite a common usage.

提交始终在keydown上触发。所以使用keydown而不是keyup。

The submit is always fired on keydown. So use keydown instead of keyup.

<input type="text"  v-on="keydown:addCategory | key 'enter'">