Getting Started
Events
Component Events
This page assumes you've already read the Components Basics. Read that first if you are new to components.
Watch a free video lesson on Spec School
Emitting and Listening to Events
A component can spec custom events directly in template expressions (e.g. in a v-on handler) using the built-in $emit method:
js
The $emit()
method is also available on the component instance as this.$emit()
:
js
Like components and props, event names provide an automatic case transformation. Notice we emitted a camelCase event, but can listen for it using a kebab-cased listener in the parent. As with props casing, we recommend using kebab-cased event listeners in templates.
Unlike native DOM events, component emitted events do not bubble. You can only listen to the events emitted by a direct child component. If there is a need to communicate between sibling or deeply nested components, use an external event bus or a global state management solution.
Declaring Emitted Events
A component can explicitly declare the events it will emit using the emits option:
js
The emits
option also supports an object syntax, which allows us to perform runtime validation of the payload of the emitted events:
js
Although optional, it is recommended to define all emitted events in order to better document how a component should work. It also allows Spec to exclude known listeners from fallthrough attributes, avoiding edge cases caused by DOM events manually dispatched by 3rd party code.
All extra arguments passed to $emit() after the event name will be forwarded to the listener. For example, with $emit('foo', 1, 2, 3) the listener function will receive three arguments.
React Essentials
Building Your Application
TypeScript