Hack Frontend Community

How to Efficiently Pass Data Between Components?

Understanding the difference between props and emit in Vue.js and how to efficiently pass data between components.

Difference Between props and emit

In Vue.js props and emit play key roles in passing data between components, but perform opposite tasks:

  • props allow passing data from parent to child component.
  • emit is used to pass data from child component to parent through events.

How Do props Work?

Props allow parent component to pass data to child. This data cannot be modified inside child component.

Props Usage Example:

<script setup>
defineProps(['message']);
</script>

<template>
  <p>Message: {{ message }}</p>
</template>

Parent Component:

<template>
  <ChildComponent message="Hello, Vue!" />
</template>
  • message is passed to ChildComponent, but inside it remains immutable.

How Does emit Work?

When child component needs to send data to parent, emit is used. This is convenient, for example, when handling button or input events.

emit Usage Example:

Child Component:

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

const emit = defineEmits(['updateMessage']);
</script>

<template>
  <button @click="emit('updateMessage', 'New message')">Change message</button>
</template>

Parent Component:

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

const message = ref('Initial message');
</script>

<template>
  <p>Message: {{ message }}</p>
  <ChildComponent @updateMessage="(newMsg) => message = newMsg" />
</template>
  • Here child component sends new message value to parent component.

v-model

If you need to synchronize data between parent and child components, v-model is used.

Parent Component:

<ChildComponent v-model="parentMessage" />

Child Component:

<script setup>
defineProps(['modelValue']);
const emit = defineEmits(['update:modelValue']);
</script>

<template>
  <input :value="modelValue" @input="emit('update:modelValue', $event.target.value)" />
</template>
  • Now parentMessage will update when value changes in ChildComponent.

When to Use props, emit and v-model?

What do you need to do?What to use?
Pass data from parent to childprops
Send event from child to parentemit
Two-way data bindingv-model

Summary

  • props are used to pass data down component hierarchy.
  • emit allows child components to send data to parents.
  • v-model is convenient for two-way data binding.

Proper understanding of these mechanisms makes code more structured and manageable!