Using Props and Emitting Events: A Guide to Parent-Child Communication in Vue 3 Components

Communication between parent and child components is essential in Vue 3. Props are used to pass data from parent to child, while events are emitted by the child to notify the parent about actions.

Using Props

Props are defined in the child component and passed from the parent:

<!-- Parent.vue -->
<ChildComponent :message="parentMessage" />

<script>
export default {
  data() {
    return { parentMessage: 'Hello from Parent' };
  },
};
</script>
vue

Copy code
<!-- ChildComponent.vue -->
<template>
  <p>{{ message }}</p>
</template>

<script>
export default {
  props: ['message'],
};
</script>

Emitting Events

Child components can emit events to communicate actions back to the parent:

<!-- ChildComponent.vue -->
<template>
  <button @click="$emit('childEvent', 'Child says hi!')">Click Me</button>
</template>
vue

Copy code
<!-- Parent.vue -->
<ChildComponent @childEvent="handleChildEvent" />

<script>
export default {
  methods: {
    handleChildEvent(data) {
      console.log(data);
    },
  },
};
</script>

Leave a comment

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