DEV Community

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

Posted on • Edited 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 an easiest way to handle this situation is with a regular form tag:

<form @submit.prevent="showMessage">
    <input v-model="message" />
    <button type="submit">click me</button>
</form>

<script>
data: () => ({
    message: '',
}),
methods: {
    showMessage() {
        return console.log(this.message)
    }
}
</script>
Enter fullscreen mode Exit fullscreen mode

Bonus - using the setup tag with the Composition API in Vue 3

<template>
  <form @submit.prevent="showMessage">
    <input v-model="message" />
    <button type="submit">click me</button>
  </form>
</template>

<script setup>
import { ref } from 'vue'

const message = ref('')

const showMessage = () => {
  console.log(message.value)
}
</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 (2)

Collapse
 
alvin_wang_33bfdaa0a745ad profile image
Alvin Wang • Edited

Why your input html leak the "/"
<input />

Collapse
 
arielmejiadev profile image
Ariel Mejia

Thanks, already fixed