Overview
Provide and inject enable dependency injection in Vue components, allowing ancestor components to serve as dependency providers for all descendants, regardless of component hierarchy depth.Basic Usage
Providing Values
Injecting Values
Function Signatures
provide
runtime-core/src/apiInject.ts:10-13
inject
runtime-core/src/apiInject.ts:36-46
Type-Safe Injection
InjectionKey
UseInjectionKey for type-safe provide/inject:
runtime-core/src/apiInject.ts:8
Shared Keys File
Create a shared file for injection keys:Default Values
Static Defaults
Factory Defaults
For expensive computations, use factory functions:runtime-core/src/apiInject.ts:42-46
Reactivity
Providing Reactive Data
Injecting Reactive Data
Readonly Injection
Prevent child components from mutating provided state:Implementation Details
provide Implementation
runtime-core/src/apiInject.ts:10-34
inject Implementation
runtime-core/src/apiInject.ts:47-85
Injection Context
hasInjectionContext
Check if inject can be safely called:runtime-core/src/apiInject.ts:92-94
Useful for library authors:
App-Level Provide
Global Providers
Plugin Injection
Common Patterns
Theme Provider
Store Provider
API Client Provider
Best Practices
- Use InjectionKey for type safety in TypeScript
- Provide readonly refs to prevent child mutations
- Create composable factories for complex providers
- Document injection keys in a shared file
- Provide mutation methods alongside state
- Check injection context in reusable composables
- Use Symbol keys to avoid naming conflicts
- Provide defaults for optional injections
Comparison with Props
When to Use Provide/Inject
- Passing data through many layers of components
- Sharing global/feature-level state
- Plugin and library APIs
- Avoiding prop drilling
When to Use Props
- Direct parent-child communication
- Explicit component APIs
- Type-safe component contracts
- Better refactoring support
Limitations
- Not reactive by default: Wrap values in refs for reactivity
- Prototype chain lookup: May impact performance in deep hierarchies
- Implicit dependencies: Less obvious than props
- Testing complexity: Requires proper test setup
Related APIs
- Props - Learn about component props
- Composables - Learn about reusable composition functions
- Application API - Learn about app-level APIs