provide/inject
provide lets an ancestor offer data that any descendant can inject, skipping the props in between.
In this page:
Syntax
// ancestor
provide() {
return { key: value };
}
// descendant
inject: ['key']
provide/inject
An ancestor calls provide("key", value) and any deeper component calls inject("key"). It avoids prop drilling through many layers.
To keep it reactive, provide a ref or reactive object, and consider providing functions to change it.
App-level provide makes values available everywhere.
Note:
Use symbols as keys in libraries to avoid name clashes.
Example: 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
- Providing plain values and expecting reactivity
- Overusing provide/inject for everything
- Mutating injected state from anywhere
Chapter Summary
- provide offers, inject receives
- Skips intermediate props
- Provide refs to stay reactive
- Do not overuse it
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: