Vue 3 Basic
How do parent and child components communicate in Vue?
Parent → Child: props
The parent passes data to the child via props.
<!-- Parent.vue -->
<template>
<Child :message="greeting" :count="num" />
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const greeting = ref('Hello!')
const num = ref(42)
</script>
<!-- Child.vue -->
<template>
<p>{{ message }} ({{ count }})</p>
</template>
<script setup>
const props = defineProps({
message: String,
count: {
type: Number,
required: true,
default: 0
}
})
</script>
Child → Parent: emit
The child emits an event (with optional payload) that the parent listens to.
<!-- Child.vue -->
<template>
<button @click="sendData">Submit</button>
</template>
<script setup>
const emit = defineEmits(['update', 'delete'])
function sendData() {
emit('update', { id: 1, value: 'new value' })
}
</script>
<!-- Parent.vue -->
<template>
<Child @update="handleUpdate" />
</template>
<script setup>
function handleUpdate(payload) {
console.log('Received from child:', payload)
}
</script>
Parent Accessing Child: defineExpose + template ref
<!-- Child.vue -->
<script setup>
import { ref } from 'vue'
const count = ref(0)
function reset() { count.value = 0 }
// Must expose explicitly
defineExpose({ count, reset })
</script>
<!-- Parent.vue -->
<template>
<Child ref="childRef" />
<button @click="childRef.reset()">Reset</button>
</template>
<script setup>
import { ref } from 'vue'
const childRef = ref(null)
</script>
Summary
| Direction | Method |
|---|---|
| Parent → Child | props |
| Child → Parent | emit |
| Parent accesses child | ref + defineExpose |
| Two-way binding | v-model |
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
