DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Create a press "enter" Event on VueJS
Ariel Mejia
Ariel Mejia

Posted on

Create a press "enter" Event on VueJS

Modifiers

In VueJS we have "v-on" or "@" directives to get an event and display something:

<input v-model="message">
<button type="submit" @click="showMessage">click me</button>
<script>
...
data: () => ({
    message: '',
}),
methods: {
    showMessage() {
        return console.log(this.message)
    }
}
</script>
Enter fullscreen mode Exit fullscreen mode

In this case the directive throws the method "showMessage", then it displays a console with the message.

But if I need to set an event to execute the "showMessage" method by press enter on input?

Well there is another modifier for this behavior:

<input v-model="message" @keyup.enter="showMessage">
<button type="submit" @click="showMessage">click me</button>
<script>
...
data: () => ({
    message: '',
}),
methods: {
    showMessage() {
        return console.log(this.message)
    }
}
</script>
Enter fullscreen mode Exit fullscreen mode

By simple adding a directive "keyup" and adding the modifier ".enter" then it would catch the event and execute the method "showMessage", well this would be ok in many scenarios a most easy way to handle this situation is with a regular form tag:

<form @submit.prevent="showMessage">
    <input>
    <button type="submit">click me</button>
</form>
<script>
...
data: () => ({
    message: '',
}),
methods: {
    showMessage() {
        return console.log(this.message)
    }
}
</script>
Enter fullscreen mode Exit fullscreen mode

In this case we are still using a modifier but this time it is used in the form tag by adding "@submit" directive and the modifier ".prevent", this would make a prevent default on submit to avoid refreshing the page and then execute the "showMessage" method.

In this post I show a little example of the VueJS modifiers but there are a lot more, just search in the docs, thanks for reading.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.