What does the `v-on` directive do?
The v-on directive is used to listen for events and call methods in response to user actions or browser events.
In other words:
v-onbinds an event (click, input, change, keyup, etc.) to a handler in the component.
This is Vue's main mechanism for handling events.
Basic usage
html
<button v-on:click="handleClick">Click</button>Shorthand (used almost always):
html
<button @click="handleClick">Click</button>What does v-on do under the hood?
It:
- finds the DOM element
- subscribes to the event (
addEventListener) - calls the component's method when the event fires
Example
vue
<template>
<input @input="onInput">
</template>
<script>
export default {
methods: {
onInput(e) {
console.log("Entered:", e.target.value)
}
}
}
</script>What can you pass to the handler?
Calling a method
html
<button @click="increase">+</button>An inline expression
html
<button @click="count++">+</button>Arguments
html
<button @click="sayHello('Vue')">Hello</button>The event object
html
<button @click="handle($event)">Click</button>v-on modifiers
Vue supports many modifiers for working with events:
Controlling propagation:
html
@click.stop <!-- event.stopPropagation() -->
@click.prevent <!-- event.preventDefault() -->
@click.stop.preventRunning once:
html
@click.onceTriggering only when clicking the element itself:
html
@click.selfCapturing phase:
html
@click.capturePassive listeners:
html
@scroll.passiveKey modifiers:
html
@keyup.enter
@keyup.esc
@keyup.ctrl.enterUsing it with components
You can listen for events that a component itself emits:
html
<MyButton @click="submit" />If the component internally calls:
js
this.$emit('click')then v-on will fire.
Dynamic event name
You can subscribe to an event whose name is computed:
html
<button v-on:[dynamicEvent]="onEvent">js
dynamicEvent = "dblclick"Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.