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

har*_*ryg 31 html javascript vue.js

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

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

   <!-- more form fields -->
   <button type="submit">Submit Form</button>
</form>
</div>
Run Code Online (Sandbox Code Playgroud)

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

new Vue({
    el: '#myVueForm',

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

尽管有这样的preventDefault();调用,当用户在文本输入上按下输入时,表单仍然提交(尽管addCategory()方法确实触发).这种行为可以在这个小提琴中得到证明.

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

bra*_*is7 45

这是Vue.js 2.x的解决方案:

<input type='text' v-on:keydown.enter.prevent='addCategory' />
Run Code Online (Sandbox Code Playgroud)

  • 不需要添加addCategory方法,只需&lt;input type ='text'v-on:keydown.enter.prevent /&gt;就足够了。 (3认同)
  • 您的编辑被拒绝,但更符合问题.我无法弄清楚如何"接受"它,但我做了改变.谢谢@Leng. (2认同)

Seb*_*tte 41

提交总是在keydown上解雇.所以使用keydown而不是keyup.

<input type="text"  v-on="keydown:addCategory | key 'enter'">
Run Code Online (Sandbox Code Playgroud)

  • @ keydown.enter.prevent = "addCategory" (12认同)
  • 这帮助了我&lt;input type =“ text” v-on:keydown.enter.prevent =“ addCategory”&gt;` (3认同)
  • 也可以使用`@keyup.enter="addCategory"`。但不要忘记表单元素上的“@submit.prevent”。在 Vue v2.6.11 上测试。 (3认同)

Cle*_*lem 30

为什么不禁用表单提交?

<form v-on:submit.prevent><input .../></form>
Run Code Online (Sandbox Code Playgroud)

  • 对于现代Vue:@ submit.prevent (6认同)
  • 如果您的表单只包含 1 个元素,这将不起作用,然后输入总是被提交。见 /sf/answers/848623751/ (3认同)
  • 是的,它会。它不会阻止提交表单。它捕获事件并阻止浏览器表单的默认行为。Submit.prevent 类似于 v-on:submit=(e) =&gt; e.preventDefault()。 (2认同)

小智 12

您可以使用禁用提交事件:

<form @submit.prevent="">
Run Code Online (Sandbox Code Playgroud)

然后当您需要提交表单时,请使用以下内容:

<button type="submit" @click="mySubmitMethod"> Send </button>
Run Code Online (Sandbox Code Playgroud)


fre*_*ett 10

对于那些只是想阻止表单在输入时提交,但不想在输入上触发任何方法的人,您可以简单地执行以下操作:

<input type="text" @keypress.enter.prevent />
Run Code Online (Sandbox Code Playgroud)

或者在自定义组件上包含native修饰符:

<custom-input type="text" @keypress.enter.native.prevent />
Run Code Online (Sandbox Code Playgroud)

优美易读且简洁。


Ryu*_*yun 9

你可以做Vue.js 1.0:

<input type="text" @keyup.enter.prevent="addCategory">
Run Code Online (Sandbox Code Playgroud)

  • 您需要使用`@keydown`,否则表单已经提交,您无法阻止它. (9认同)

小智 7

您可以使用此:

的HTML

<form name="..." @submit.prevent="onSubmitMethod">
Run Code Online (Sandbox Code Playgroud)

JS

methods: {
  onSubmitMethod() {

  }
}
Run Code Online (Sandbox Code Playgroud)