Props vs Emit in Vue.js: Key Differences and Usage

Props vs Emit in Vue.js: Key Differences and Usage

Vue.js provides an efficient way for components to communicate with each other using props and emit. Understanding when to use each is crucial for building scalable and maintainable applications. In this article, we’ll explore the differences between props and emit, their use cases, and best practices.

1. Props (props)

Props are used to pass data from a parent component to a child component. They are read-only and should not be mutated inside the child component.

Key Characteristics of Props

  • Allows one-way data flow from parent to child.
  • Must be declared in the child component.
  • Cannot be modified inside the child component.

Example: Passing props from parent to child

<!-- ParentComponent.vue -->
<template>
  <ChildComponent :message="'Hello from Parent!'" />
</template>

<script setup>
import ChildComponent from './ChildComponent.vue';
</script>
<!-- ChildComponent.vue -->
<template>
  <p>{{ message }}</p>
</template>

<script setup>
defineProps({
  message: String
});
</script>

Here, message is passed as a prop from ParentComponent to ChildComponent.

2. Emit (emit)

Emit is used for event-driven communication, allowing a child component to send data back to its parent component.

Key Characteristics of Emit

  • Enables child-to-parent communication.
  • Sends custom events to notify the parent of changes.
  • The parent component listens for emitted events and handles them.

Example: Emitting an event from child to parent

<!-- ParentComponent.vue -->
<template>
  <ChildComponent @update-message="handleMessage" />
</template>

<script setup>
import ChildComponent from './ChildComponent.vue';

const handleMessage = (newMessage) => {
  console.log('Received from child:', newMessage);
};
</script>
<!-- ChildComponent.vue -->
<template>
  <button @click="sendMessage">Click Me</button>
</template>

<script setup>
import { defineEmits } from 'vue';

const emit = defineEmits(['update-message']);

const sendMessage = () => {
  emit('update-message', 'Hello from Child!');
};
</script>

Here, ChildComponent emits an event (update-message) with data, and the parent listens for it.

Leave a comment

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