Vue parent-child component communication relies on three key mechanisms: props for parent-to-child data passing, $emit for child-to-parent method triggering, and ref for direct parent access to child components.
Parent Component (Parent.vue)
<template>
<div class="parent-wrapper">
<h3>Parent Component</h3>
<ChildComponent
ref="childInstance"
:parentData="parentContent"
@updateParentContent="updateParentData"
/>
</div>
</template>
<script>
import ChildComponent from './Child.vue';
export default {
components: { ChildComponent },
data() {
return {
parentContent: "Initial Parent Value"
};
},
methods: {
updateParentData(updatedValue) {
this.parentContent = updatedValue;
}
}
};
</script>
Child Component (Child.vue)
<template>
<div class="child-wrapper">
<h4>Child Component</h4>
<p>Data from Parent: {{ parentData }}</p>
<button @click="triggerParentUpdate">Update Parent Component Value</button>
</div>
</template>
<script>
export default {
props: {
parentData: {
type: String,
required: true
}
},
methods: {
triggerParentUpdate() {
// Emit an event to trigger parent component's method with a new value
this.$emit('updateParentContent', 'Value Updated from Child');
}
}
};
</script>
Key Details:
-
Parent-to-Child Data Passing
Use thepropsoption in the child comopnent to define accepted data from the parent. The parent binds its data to the child using thev-binddirective (shorthand:) to pass values down. Props enforce type checking (here,Stringtype forparentData) to ensure data integrity. -
Child-to-Parent Method Triggering
To update parent data from the child, the child component usesthis.$emit()to fire a custom event (e.g.,updateParentContent) that the parent has registered viav-on(shorthand@). The child can pass a payload (the updated value) to the parent's handler method, which modifies the parent's internal state. -
Parent Access to Child Methods via
ref
Adding arefattribute to the child component in the parent's template (e.g.,ref="childInstance") allows direct access to the child component instance. The parent can call child methods usingthis.$refs.childInstance.[childMethodName](), eliminating the need for DOM querying.
Using ref is more efficient than traditioanl DOM traversal methods like document.querySelector(), as it directly references the Vue component instance instead of searching the DOM tree, reducing performance overhead.