The following is an example of parent-child components written in Vue 3, including passing data and calling parent component methods:
ChildComponent.vue:
<template>
<div>
<p>Child Component</p>
<p>Message: {
{ message }}</p>
<button @click="updateMessage">Update Message</button>
</div>
</template>
<script>
import {
defineEmits, defineProps } from 'vue';
export default {
props: {
initialMessage: {
type: String,
required: true
}
},
emits: ['update:message'],
setup(props, {
emit }) {
const message = defineProps({
message: props.initialMessage
});
function updateMessage() {
message.message = 'Hello Vue 3';
emit('update:message', message.message);
}
return {
message,
updateMessage
};
}
}
</script>
In the above code, we defined a ChildComponent
child component called and declared a initialMessage
props property called props which is of type string and is required. We also define a update:message
custom event called , which is used to pass the updated message back to the parent component.
In setup()
the function, we use defineProps()
the function to create a reactive message
object and set its initial value to props.initialMessage
. We then defined a method called , which will be updated updateMessage()
when the button is clicked , and fire the event by calling a function and passing the updated message to the parent component.message.message
'Hello Vue 3'
emit()
update:message
ParentComponent.vue:
<template>
<div>
<p>Parent Component</p>
<child-component :initial-message="message" @update:message="onUpdateMessage"></child-component>
<p>Updated Message: {
{ updatedMessage }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
import {
ref } from 'vue';
export default {
components: {
ChildComponent
},
setup() {
const message = ref('Hello World');
const updatedMessage = ref('');
function onUpdateMessage(value) {
updatedMessage.value = value;
}
return {
message,
updatedMessage,
onUpdateMessage
};
}
}
</script>
In the code above, we defined a ParentComponent
parent component named , and used tags in the template <child-component>
to introduce the child component. We message
bind the property to the property of the child component initial-message
, and listen to the event fired by the child component update:message
to get the updated message.
In setup()
the function, we use ref()
the function to create two reactive variables: message
and updatedMessage
. We also define a onUpdateMessage()
method named , which is called when the child component fires update:message
an event, to save the updated message to updatedMessage
a variable.
This is a complete parent-child component example, including passing data and calling parent component methods.