User interaction drives every app; modifiers remove most event boilerplate.
`v-on`, shortened to @, attaches a listener: @click="handler". The value can be:
- A method name:
@click="save"callssave(event)with the native event. - An inline statement:
@click="count++"or@click="remove(item.id)". If you also need the event, pass the special$eventvariable:@click="remove(item.id, $event)".
Event modifiers handle common chores declaratively:
.preventcallspreventDefault(), e.g.@submit.prevent="onSubmit"stops the page reload..stopstops propagation;.selffires only if the event target is the element itself..onceremoves the listener after the first call;.passivemarks scroll/touch listeners as passive;.captureuses the capture phase.
Key modifiers filter keyboard events: @keyup.enter="send", @keydown.esc="close", and combinations with system keys like @keyup.ctrl.enter. Add .exact to require exactly those modifiers. Mouse buttons have .left, .right and .middle.
Handlers are functions declared in <script setup>. Keep template statements short; once a handler does more than one thing, move it into a function. Vue removes listeners automatically when the component unmounts, so you never clean up template listeners yourself (only listeners you add manually with addEventListener).
Example
<script setup>
import { ref } from 'vue'
const message = ref('')
const log = ref([])
function send() {
if (!message.value.trim()) return
log.value.push(message.value)
message.value = ''
}
function remove(i, event) {
console.log('clicked', event.target.tagName); log.value.splice(i, 1) // clicked BUTTON
}
</script>
<template>
<form @submit.prevent="send">
<input v-model="message" @keydown.esc="message = ''">
<button>Send</button>
</form>
<p v-for="(m, i) in log" :key="i">
{{ m }} <button @click="remove(i, $event)">x</button>
</p>
</template>Remember
@event="method"or an inline statement; use$eventfor the native event.prevent,.stop,.once,.selfreplace manual event-object calls- Key modifiers like
@keyup.enterfilter keyboard events
Watch out for
- Forgetting
.preventon a form's submit so the browser reloads the page.