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:
propsallow passing data from parent to child component.emitis 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>
messageis passed toChildComponent, 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
messagevalue 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
parentMessagewill update when value changes inChildComponent.
When to Use props, emit and v-model?
| What do you need to do? | What to use? |
|---|---|
| Pass data from parent to child | props |
| Send event from child to parent | emit |
| Two-way data binding | v-model |
Summary
propsare used to pass data down component hierarchy.emitallows child components to send data to parents.v-modelis convenient for two-way data binding.
Proper understanding of these mechanisms makes code more structured and manageable!