A child component can access the parent component when the child is placed in the following fashion:
<parent>
<child></child>
</parent>
Code language: HTML, XML (xml)
I’m demonstrating the same here with a code example. Let’s assume that we have a vehicle component, inside which we can pass the child component called car. The vehicle component can have it’s own independent properties and the child can have too. We can further pass in other components like motorcycle to the vehicle component as well. We can then access any property of the vehicle component from within the child component using the $parent accessor.
Here’s my App.vue file:
<template>
<div id="app">
<vehicle>
<car></car>
</vehicle>
<vehicle>
<motorcycle></motorcycle>
</vehicle>
<small>wwww.nightprogrammer.com</small>
</div>
</template>
<script>
export default {
name: "App",
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
}
</style>
Code language: HTML, XML (xml)
And here’s my main.js file:
import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
Vue.component("vehicle", {
data() {
return {
name: "Vehicle component"
};
},
template: `
<div>
<h2>Vehicle section</h2>
<p><slot></slot></p>
</div>
`
});
Vue.component("car", {
template: `<p>Car inside {{parentName}}</p>`,
computed: {
parentName() {
return this.$parent.name;
}
}
});
Vue.component("motorcycle", {
template: `<p>Motorcycle inside {{parentName}}</p>`,
computed: {
parentName() {
return this.$parent.name;
}
}
});
new Vue({
render: (h) => h(App)
}).$mount("#app");
Code language: JavaScript (javascript)
As you can see in the above code, I’ve got a vehicle component on line 6. This component has a h2 of Vehicle section as it’s content. And then a slot to place a child component. If you want to learn about slots, you can read my previous article on creating a simple layout with v-slot. Then inside the car component, I’ve accessed name property of the parent component using $parent.name on line 24.
The output of the above code would look like this:
You can find a working version of the above code from my repos below: