Vue.js Components — Parent, Child and Root

John Au-Yeung
DataSeries
Published in
4 min readMar 28, 2020

--

Photo by Israel Sundseth on Unsplash

DataSeries highlight:

  • Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at how to access various parts of a parent, child, or root component. Also, we look at dependency inject in Vue.js

Element & Component Access

Sometimes we have to access other components from a given component. However, it’s a bad idea to do this often since it gets messy fast.

Accessing the Root Instance

We can access the root instance of from a child component with the $root property.

For example, we can access the root Vue instance’s foo property as follows:

src/index.js :

Vue.component("foo", {
template: `<p>{{rootFoo}}</p>`,
computed: {
rootFoo() {
return this.$root.foo;
}
}
});
new Vue({
el: "#app",
data: {
foo: "bar"
}
});

index.html :

<!DOCTYPE html>
<html>
<head>
<title>App</title>
<meta charset="UTF-8" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<foo></foo>
</div>
<script…

--

--