← Back to Vue.js Course | Chapter 6: Component Communication | Lesson 4 of 7

$parent/$root

$parent and $root reach up the component tree, but they create tight coupling and should be a last resort.

In this page:

  1. $parent/$root
Syntax
markup
this.$parent
this.$root

$parent/$root

this.$parent is the immediate parent instance and this.$root is the root instance of the app. They work, but a child that reads its parent's data is hard to reuse and test.

Prefer props, events, provide/inject or a store, and reserve these for tightly coupled component families.

Note: If you reach for $parent often, consider provide/inject or a store instead.

Example: $parent/$root

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <wrapper-box></wrapper-box>
</div>
<script>
  const app = Vue.createApp({ data() { return { appName: "Shop" }; } });
  app.component("wrapper-box", { data() { return { label: "wrapper" }; }, template: "<div><leaf-node></leaf-node></div>" });
  app.component("leaf-node", {
    template: "<p>{{ $root.appName }} > {{ $parent.label }}</p>",
  });
  app.mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: Shop > wrapper
-->
Live Example
Related Topics
Common Mistakes
  1. Coupling children to a specific parent
  2. Using $parent for shared state
  3. Breaking when the component tree changes
Chapter Summary
  • $parent is the immediate parent
  • $root is the app root
  • They create tight coupling
  • Prefer props, events or a store
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.