Introduction to Vue.js Emit and Custom Events

Vue.js allows parent and child components to communicate with each other using custom events and the `$emit` method. This powerful feature enables bidirectional communication and the passing of data between components. In this guide, we'll explore how to effectively use custom events for parent-child communication in Vue.js.


Using `$emit` to Send Custom Events

Child components can send custom events to parent components using the `$emit` method. Parent components can listen for these events and respond accordingly. Here's an example of how to use `$emit` for communication:


<div id="app">
<child-component @custom-event="handleEvent"></child-component>
<p>Received in parent: {{ message }}</p>
</div>
<script>
Vue.component('child-component', {
template: '<button @click="emitEvent">Click me!</button>',
methods: {
emitEvent: function() {
this.$emit('custom-event', 'Hello from the child component!');
}
}
});
new Vue({
el: '#app',
data: {
message: ''
},
methods: {
handleEvent: function(data) {
this.message = data;
}
}
});
</script>

In this example, the child component emits a custom event with a message using `$emit`, and the parent component listens for the event and handles the message.


Passing Data with Custom Events

Custom events can carry data from the child component to the parent component. This data can be used to update the parent's state or perform other actions. Here's an example of passing data with a custom event:


<div id="app">
<child-component @custom-event="updateParentData"></child-component>
<p>Received in parent: {{ receivedData }}</p>
</div>
<script>
Vue.component('child-component', {
template: '<button @click="emitData">Send Data</button>',
methods: {
emitData: function() {
this.$emit('custom-event', { message: 'Data from the child', value: 42 });
}
}
});
new Vue({
el: '#app',
data: {
receivedData: ''
},
methods: {
updateParentData: function(data) {
this.receivedData = `Message: ${data.message}, Value: ${data.value}`;
}
}
});
</script>

In this example, the child component emits a custom event with data, and the parent component receives and processes the data.


Conclusion

Vue.js custom events and the `$emit` method provide an effective way for parent and child components to communicate and share data. This feature enhances the reusability and flexibility of Vue components, making it easier to build dynamic and interactive web applications.