Categories
Vue Answers

How to emit event from parent to child component with Vue 3?

Spread the love

In Vue 3, you can emit events from a parent component to a child component using the Composition API along with the provide and inject functions.

To achieve this, we do the following:

1. Parent Component (Emitter)

In the parent component, define a function to emit an event and provide it to the child component using provide.

2. Child Component (Receiver)

In the child component, use inject to access the emitted event function from the parent.

For example:

<!-- ParentComponent.vue -->
<template>
  <div>
    <button @click="emitToChild">Send Event to Child</button>
    <ChildComponent />
  </div>
</template>

<script>
import { defineComponent, provide } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default defineComponent({
  components: {
    ChildComponent,
  },
  setup() {
    // Define a function to emit an event
    const emitToChild = () => {
      // Emit the event to the child component
      emitEvent('customEvent');
    };

    // Provide the event emitting function to child components
    provide('emitEvent', emitToChild);

    return {
      emitToChild,
    };
  },
});
</script>
<!-- ChildComponent.vue -->
<template>
  <div>
    <p>Child Component</p>
  </div>
</template>

<script>
import { defineComponent, inject } from 'vue';

export default defineComponent({
  setup() {
    // Inject the event emitting function from the parent
    const emitEvent = inject('emitEvent');

    return {
      emitEvent,
    };
  },
});
</script>

In this example, the ParentComponent emits a custom event when the button is clicked.

The ChildComponent injects the event emitting function from the parent and can then call it when needed.

This pattern allows you to pass data or trigger actions from parent to child components in Vue 3 applications.

Adjust the event name and data payload as needed for your specific use case.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *