Vue Tip: Pass Custom Arguments to Event Handler Method
In Vue, we use the v-on
(typically shortened with the @
symbol) to listen to DOM events and run some JavaScript code when triggered.
We can use inline handlers or method handlers if the logic for the event handler is more complex:
1<script setup>
2const name = ref('Vue.js')
3
4const greet = (event) => {
5 alert(`Hello ${name.value}!`)
6 if (event) {
7 alert(event.target.tagName)
8 }
9}
10</script>
11
12<template>
13 <button @click="greet">Greet</button>
14</template>
Sometimes we need to pass custom arguments to the method and access the original DOM event:
1<script setup>
2const name = ref('Vue.js')
3
4const greet = (event, name) => {
5 alert(`Hello ${name.value}!`)
6 if (event) {
7 alert(event.target.tagName)
8 }
9}
10</script>
11
12<template>
13 <button @click="greet($event, “Michael”)">Greet</button>
14</template>
The original DOM event is accessible via the unique $event
variable. Custom arguments can be added by calling the method in an inline handler instead of directly binding it to a method name.
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Avoid Mutating a Prop Directly
Mutating props is an anti-pattern. You should use computed properties instead.
Vue Tip: Access DOM in Watcher Callback After Vue Updated It
To access the DOM after Vue has updated it in a watcher callback, you can use the flush post option.'