Handling Enter Key in Vue.js
Event Modifiers
You can refer to event modifiers in vuejs to prevent form submission on enter
key.
It is a very common need to call
event.preventDefault()
orevent.stopPropagation()
inside event handlers.
Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.
To address this problem, Vue provides event modifiers for
v-on
. Recall that modifiers are directive postfixes denoted by a dot.
<form v-on:submit.prevent="<method>">
...
</form>
As the documentation states, this is syntactical sugar for e.preventDefault()
and will stop the unwanted form submission on press of enter key.
Here is a working fiddle.
new Vue({
el: '#myApp',
data: {
emailAddress: '',
log: ''
},
methods: {
validateEmailAddress: function(e) {
if (e.keyCode === 13) {
alert('Enter was pressed');
} else if (e.keyCode === 50) {
alert('@ was pressed');
}
this.log += e.key;
},
postEmailAddress: function() {
this.log += '\n\nPosting';
},
noop () {
// do nothing ?
}
}
})
html, body, #editor {
margin: 0;
height: 100%;
color: #333;
}
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="myApp" style="padding:2rem; background-color:#fff;">
<form v-on:submit.prevent="noop">
<input type="text" v-model="emailAddress" v-on:keyup="validateEmailAddress" />
<button type="button" v-on:click="postEmailAddress" >Subscribe</button>
<br /><br />
<textarea v-model="log" rows="4"></textarea>
</form>
</div>
In vue 2, You can catch enter event with v-on:keyup.enter
check the documentation:
https://v2.vuejs.org/v2/guide/events.html#Key-Modifiers
I leave a very simple example:
var vm = new Vue({
el: '#app',
data: {msg: ''},
methods: {
onEnter: function() {
this.msg = 'on enter event';
}
}
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
<input v-on:keyup.enter="onEnter" />
<h1>{{ msg }}</h1>
</div>
Good luck