JAVASCRIPT
Vue 3 Provide and Inject for Dependency Injection
Share reactive data across deeply nested components in Vue 3 without prop drilling using provide and inject.
// ParentComponent.vue
import { provide, ref } from 'vue';
export default {
setup() {
const theme = ref('dark');
provide('themeKey', theme);
}
};
// ChildComponent.vue
import { inject } from 'vue';
export default {
setup() {
const theme = inject('themeKey', 'light');
return { theme };
}
};
How it works: Provide and inject mechanism in Vue 3 enables a parent component to serve as a dependency injector for all its descendants, regardless of how deep the component tree goes, avoiding cumbersome prop passing.