In Vue, you can listen for events using the v-on
directive or the shorthand @
. You can listen for any DOM event; for example, you can use @click
for click events. This link contains a list of all native DOM events.
Define Events
Of course, you can also listen for custom events that you have defined in your child component:
Handle Events
Let's look at the different ways to handle such events in Vue.
Without arguments
If your event does not have any arguments, I prefer this syntax:
Access custom event object
If you want to access the custom event object in your event handler, you can use the following syntax:
Access custom & native event object
Sometimes, you need access to your custom event object and the native event object. In this case, you can use the following syntax:
Further Reading
Lachlan Miller wrote an excellent in-depth article about event handling, which you can find here. It is definitely worth a read!
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: Use Your Composables Synchronously
You should always call your composables synchronously in setup() hook or <script setup>. Otherwise Vue will not be able to determine the current active component instance and cannot correctly register features like lifecycle hooks, watchers, and computed properties.
Nuxt Tip: Detecting Server vs. Client-Side Code Execution
Nuxt 3 provides a way to detect whether your code is running on the server or client-side.