In VueJS we have v-on
or @
directives to get an event and display something:
<script setup>
const message = ref('');
const showMessage = function () {
console.log(message);
}
</script>
<template>
<input v-model="message">
<button type="submit" @click="showMessage">click me</button>
</template>
In this case the directive @click
fired the method showMessage
Well, there is another modifier for this behavior, lets supposed that we need to tight a press-enter event and fire showMessage
:
<script setup>
const message = ref('');
const showMessage = function () {
console.log(message);
}
</script>
<template>
<input v-model="message" @keyup.enter="showMessage">
<button type="submit" @click="showMessage">click me</button>
</template>
When user press enter and key up event is fired, it would catch the event and execute the method showMessage
,
well this would be ok in many scenarios like a search-box
For regular forms the event submit and it's modifiers like prevent
are pretty useful an Eg:
<script setup>
const message = ref('');
const showMessage = function () {
console.log(message);
}
</script>
<template>
<form @submit.prevent="showMessage">
<input v-model="message">
<button type="submit">click me</button>
</form>
</template>
Thanks for reading!
Sign up & get tips and tricks
You'll get monthly updates regarding my most recent articles and products.