In Vue, "emit" is a method provided by Vue instances and components to communicate upwards in the component tree.
It allows child components to trigger events that parent components can listen to and respond to.
This is commonly used for child components to notify parent components about certain actions or changes.
this.$emit(eventName, eventData);
eventName: The name of the custom event you want to emit.
eventData (optional): The data you'd like to pass along with the eventName.
Child Component Emits an Event using `$emit` to trigger a custom event along the payload.
emitEvent() { this.$emit('child-event', 'Hello from child component!'); }
<button @click="emitEvent" > Click me! </button>
Mapped Event Emitter function with element in template.
<template> <button @click="emitEvent"> Click me! </button> </template> <script> export default { methods: { emitEvent() { this.$emit('child-event', 'Hello from child component!'); } } } </script>
<ChildComponent @child-event="handleChildEvent" />
Listen to the Event in the Parent Component emitted from the Child Component.
Map the event with Parent Component function.
// ParentComponent.vue <template> <div> <ChildComponent @child-event="handleChildEvent" /> <p v-if="message">{{ message }}</p> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { message: '' }; }, methods: { handleChildEvent(payload) { this.message = 'Received from child component: ' + payload; } } }; </script>
The ChildComponent "emits" a custom event named 'child-event' when the button is clicked. It also passes a payload ('Hello from child component!') with `eventName`.
The ParentComponent listens for this event using the "@child-event" directive and specifies a method (handleChildEvent) to handle it.
When the event is emitted by the child component, the method "handleChildEvent" in the parent component is invoked.
It receives the payload sent by the child component, and in this example, it sets the message data property, which is then displayed in the template.
This mechanism enables a child component to emit an event and pass data along with it, and the parent component can listen for and react to it.
This way, The child component communicates with the parent component through events, making it a powerful way to build flexible and reusable Vue applications.