Loading...
Loading...
Understanding the difference between props and emit in Vue.js and how to efficiently pass data between components.
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.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.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>
message value to parent component.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>
parentMessage will update when value changes in ChildComponent.| 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 |
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!