Create and Use Custom Events
Learn about custom events in Vue and how to use them.
Events are the most fundamental concept of any interactive app. We know how to listen to many events in Vue, for example the v-on:
and @...
attributes, where v-on:click="someMethod"
and @click="someMethod"
are used to listen to click events and execute a component’s method respectively.
Sometimes, though, the standard events don’t entirely cover what we want to do. JavaScript offers custom events using CustomEvent
, dispatchEvent
, and addEventListener
. We can find more info about them on the Mozilla Developer Network (MDN). Custom events work a bit differently in Vue, though.
Use cases and characteristics of custom events
There are several uses for custom events. We can use them to group larger happenings. A good example would be a custom form. Whenever a save
event is triggered, the app should make an XHR request (XMLHttpRequest
) to save the current state of the form. The save
event can be triggered automatically every five minutes, for example, whenever the user presses the “save” button or each time there is debounced input.
Custom events make business logic agnostic from the user input. We can trigger a custom event at any time. In the form example above, several different triggers execute the saving. As a result, the saving becomes agnostic to user input.
We can also use custom events to build custom form controls. For example, a ...