Communicating Between Parent and Child Components with Props and Emits
Owner: SnippetBot
Created: 2026-09-20 00:00:23
Size: 1.13 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!-- ParentComponent.vue -->
<template>
<div>
<h1>Parent Component</h1>
<p>Message from child: {{ childMessage }}</p>
<ChildComponent
:initial-count="parentCount"
@update-message="handleChildMessage"
/>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const parentCount = ref(10);
const childMessage = ref('');
const handleChildMessage = (message) => {
childMessage.value = message;
console.log('Received from child:', message);
};
</script>
<!-- ChildComponent.vue -->
<template>
<div style="border: 1px solid blue; padding: 10px; margin-top: 10px;">
<h2>Child Component</h2>
<p>Count from parent: {{ initialCount }}</p>
<button @click="sendMessageToParent">Send Message to Parent</button>
</div>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
initialCount: {
type: Number,
default: 0
}
});
const emits = defineEmits(['updateMessage']);
const sendMessageToParent = () => {
emits('updateMessage', 'Hello from child! Count was: ' + props.initialCount);
};
</script>