Javascript is required
Mokkapps LogoMichael Hoffmann

Vue Tip: Pass Custom Arguments to Event Handler Method

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Dec 26, 2022
1 min read
|
37 views
Script
Vue Tip: Pass Custom Arguments to Event Handler Method Image

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:

Component.vue
<script setup>const name = ref('Vue.js')const greet = (event) => {  alert(`Hello ${name.value}!`)  if (event) {    alert(event.target.tagName)  }}</script><template>  <button @click="greet">Greet</button></template>

Sometimes we need to pass custom arguments to the method and access the original DOM event:

Component.vue
<script setup>const name = ref('Vue.js')const greet = (event, name) => {  alert(`Hello ${name.value}!`)  if (event) {    alert(event.target.tagName)  }}</script><template>  <button @click="greet($event, β€œMichael”)">Greet</button></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 Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.