Events
Vue components can emit custom events to communicate with parent components.
Custom events are a primary way for child components to send information or trigger actions in their parent components.
Basic Usage
Section titled “Basic Usage”- Use
$emitin the child to trigger an event. - Listen for the event in the parent using
v-onor@.
Example
Section titled “Example”this.$emit('custom-event', payload);
// Parent.vue<Child @custom-event="handleEvent" />Passing Data
Section titled “Passing Data”You can pass data as the second argument to $emit, which will be received as a parameter in the parent handler.
this.$emit('update-count', 5);
// Parent.vue<Child @update-count="count => total += count" />Event Validation
Section titled “Event Validation”Declare emitted events in the emits option for better type safety and validation (Vue 3):
export default { emits: ["custom-event", "update-count"],};Event Modifiers
Section titled “Event Modifiers”Use .native modifier in Vue 2 to listen to native DOM events on child components. In Vue 3, use emits and $attrs for similar patterns.
- Events only flow up the component tree (child to parent).
- For sibling or cross-component communication, use a global event bus or state management.