In Vue.js 2, you can use custom events to send messages from a child component to a parent component. Here’s how you can do it:
The parent component will listen for events emitted by the child component. You can define the custom event handler on the parent and bind it to the child component.
<template>
<div>
<child-component @custom-event="handleCustomEvent"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleCustomEvent(message) {
console.log('Received message from child:', message);
}
}
};
</script>
In the child component, you use $emit to send an event to the parent. The custom-event is emitted, and you can send additional data along with it.
This is a simple and effective way to pass data from a child component to a parent component in Vue 2. You can emit custom events from the child and handle them in the parent using @event-name syntax in the parent template.
Work with our skilled Vue developers to accelerate your project and boost its performance.
Hire Vuejs Developers