inject() Inject an Ancestor Dependency
Last updated: 2026-10-22
inject() Inject an Ancestor Dependency
inject() reads data provided by an ancestor, optionally falling back to a default.
| Group | Dependency Injection |
|---|---|
| Kind | API |
| Scope | Component |
| Vue Version | 3.0+ |
| SSR Support | Yes |
📝 Syntax
const theme = inject("theme") // undefined when missing
const theme = inject("theme", "light") // default value
const theme = inject("theme", () => ref("light")) // factory default (recommended)
⚙️ Arguments
| key | The key matching a provide call |
|---|---|
| defaultValue | Optional default; pass a factory to avoid shared instances |
Returns:The injected value, or the default/undefined
▶ Example
Edit the code below and see the live result:
Output:
Without a provider it shows 'Theme: light by default'.
💡 Key Points
⚠️ Warning Do not pass object literals as defaults — they are shared; use a factory.
💡 Tip Injected refs stay reactive; templates unwrap them, scripts use .value.
ℹ️ Note Callable only during setup or inside composables, synchronously.
🏷️ Related Dependency Injection
💡 Related Cases
More case studies coming soon.
📚 Related Tutorials
❓ FAQ
Q Does a missing provider throw?
A No — it returns undefined with a dev hint; defaults are safer.
Q Can injected writes affect the ancestor?
A It is the same reference, so writes propagate — usually undesirable.
Q Why a factory default?
A Each call gets a fresh instance, preventing shared-state bugs.