provide/inject का उपयोग
provide एक ancestor को ऐसा data offer करने देता है जिसे कोई भी descendant inject कर सके, बीच के props skip करते हुए।
In this page:
Syntax
// 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
<!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. #}
आम गलतियां
- plain values provide करना और reactivity की उम्मीद करना
- हर चीज़ के लिए provide/inject overuse करना
- कहीं से भी 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: