Vue.js Events: Interacting with DOM Events
Vue.js provides a convenient way to handle DOM events using the v-on directive on an element. Being able to intercept events is essential in making Vue components interactive.
What are Vue.js events?
With Vue.js, we can intercept any DOM event using the v-on directive on an element. For example, if we want to perform something when a click event occurs on an element:
1 | <template> |
We can add the v-on directive:
1 | <template> |
Vue also provides an alternative syntax for this:
1 | <template> |
You can choose to use parentheses or not. @click="handleClick"
is equivalent to @click="handleClick()"
.
The handleClick
method is attached to the component:
1 | <script> |
If you want to learn more about Vue methods, check out my Vue Methods tutorial.
Accessing the original event object
In many cases, you may need to perform an action on the event object or retrieve some properties from it. How can you access the event object?
You can use the special $event
directive:
1 | <template> |
If you want to pass additional variables:
1 | <template> |
From there, you can call event.preventDefault()
, but there’s a more elegant solution: event modifiers.
Event modifiers
Instead of manipulating the DOM directly in your methods, you can instruct Vue to handle them for you:
@click.prevent
callsevent.preventDefault()
@click.stop
callsevent.stopPropagation()
@click.passive
makes use of the passive option of addEventListener@click.capture
uses event capturing instead of event bubbling@click.self
ensures the click event was not bubbled from a child event, but directly happened on that element@click.once
triggers the event only once
You can combine multiple modifiers by appending them one after the other.
For more information on event propagation, bubbling, and capturing, refer to my JavaScript events guide.
tags: [“Vue.js”, “events”, “DOM”, “v-on”, “event modifiers”]