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

provide/inject का उपयोग

provide एक ancestor को ऐसा data offer करने देता है जिसे कोई भी descendant inject कर सके, बीच के props skip करते हुए।

In this page:

  1. provide/inject
Syntax
markup
// ancestor
provide() {
  return { key: value };
}

// descendant
inject: ['key']

provide/inject

एक ancestor provide("key", value) call करता है और कोई भी deeper component inject("key") call करता है। यह कई layers के through prop drilling avoid करता है।

इसे reactive रखने के लिए, एक ref या reactive object provide करें, और इसे बदलने के लिए functions provide करने पर विचार करें।

App-level provide values को हर जगह available बनाता है।

Note: name clashes से बचने के लिए libraries में keys की तरह symbols इस्तेमाल करें।

उदाहरण: provide/inject

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">
  <theme-panel></theme-panel>
</div>
<script>
  const app = Vue.createApp({
    setup() {
      const theme = Vue.ref("dark");
      Vue.provide("theme", theme);
      Vue.provide("toggle", () => { theme.value = theme.value === "dark" ? "light" : "dark"; });
      return {};
    },
  });
  app.component("theme-panel", { template: "<div><theme-label></theme-label></div>" });
  app.component("theme-label", {
    setup() { return { theme: Vue.inject("theme"), toggle: Vue.inject("toggle") }; },
    template: '<p>Theme: {{ theme }} <button @click="toggle">Toggle</button></p>',
  });
  app.mount("#app");
  document.querySelector("button").click();
  Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>

<!-- Output:
Rendered: Theme: light Toggle
console: Theme: light Toggle
-->
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. plain values provide करना और reactivity की उम्मीद करना
  2. हर चीज़ के लिए provide/inject overuse करना
  3. कहीं से भी injected state mutate करना
चैप्टर सारांश
  • provide offer करता है, inject receive करता है
  • intermediate props skip करता है
  • Reactive रहने के लिए refs provide करें
  • इसे overuse न करें
🔒

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.