harryg harryg - 1 year ago 291
HTML Question

Prevent form submitting when pressing enter from a text input, using Vue.js

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

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

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

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!");

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

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.

Answer Source

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

<input type="text"  v-on="keydown:addCategory | key 'enter'">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download