0 day streak
javascript / beginner
Snippet

Provide and Inject

Provide and Inject allow a parent component to serve as a dependency provider for all its descendants, regardless of how deep the component hierarchy is.

snippet.js
javascript
1
2
3
4
5
// Parent.vue
provide('theme', 'dark');
// Child.vue
const theme = inject('theme');
vue
Breakdown
1
provide('theme', 'dark');
The parent 'provides' a piece of data identified by a key ('theme').
2
inject('theme');
Any child component can 'inject' or request that data using the same key.