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

$parent/$root का उपयोग

$parent और $root component tree में ऊपर पहुँचते हैं, लेकिन ये tight coupling बनाते हैं और last resort होना चाहिए।

In this page:

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

$parent/$root

this.$parent immediate parent instance है और this.$root app का root instance है। ये काम करते हैं, लेकिन एक child जो अपने parent का data पढ़ता है reuse और test करना मुश्किल है।

Props, events, provide/inject, या एक store prefer करें, और इन्हें tightly coupled component families के लिए reserve करें।

Note: अगर आप अक्सर $parent इस्तेमाल करते हैं, इसकी बजाय provide/inject या एक store consider करें।

उदाहरण: $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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. children को एक specific parent से couple करना
  2. shared state के लिए $parent इस्तेमाल करना
  3. component tree बदलने पर टूटना
चैप्टर सारांश
  • $parent immediate parent है
  • $root app root है
  • ये tight coupling बनाते हैं
  • Props, events, या एक store prefer करें
🔒

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.