0 day streak
javascript / intermediate
Snippet

Cross-Component Communication with Provide/Inject

Provide and Inject solve the problem of 'prop drilling' where data must be passed through multiple levels of components. It allows a grand-parent component to serve as a dependency provider for any descendant.

snippet.js
javascript
1
2
3
4
5
6
7
8
// Ancestor.vue
import { provide, reactive } from 'vue';
const theme = reactive({ color: 'blue' });
provide('app-theme', theme);
// DeeplyNestedChild.vue
import { inject } from 'vue';
const theme = inject('app-theme', { color: 'default' });
vue
Breakdown
1
provide('app-theme', theme)
Registers a dependency that can be 'injected' by any component in the sub-tree.
2
inject('app-theme', ...)
Retrieves the dependency by key, with an optional default value if the provider is missing.