How to use provide/inject in Vue
Vue’s provide/inject enables dependency injection across component hierarchies, allowing ancestor components to serve as dependency providers for descendant components. As the creator of CoreUI, a widely used open-source UI library, I’ve used provide/inject in countless Vue applications to avoid prop drilling and create cleaner component architectures. From my expertise, the most effective approach is providing services and configuration at the root level and injecting them where needed. This method eliminates prop drilling while maintaining clear dependency relationships across component trees.
Use provide in ancestor components and inject in descendants to share data without prop drilling.
<!-- Parent Component -->
<template>
<div>
<ChildComponent />
</div>
</template>
<script setup>
import { provide } from 'vue'
const theme = { color: 'blue', size: 'large' }
provide('theme', theme)
</script>
<!-- Child Component (any level deep) -->
<template>
<div :style="{ color: theme.color }">
Themed content
</div>
</template>
<script setup>
import { inject } from 'vue'
const theme = inject('theme')
</script>
The provide function makes data available to all descendant components, while inject retrieves that data using the same key. This pattern works across any number of component levels without passing props through intermediate components.
Best Practice Note:
This is the same provide/inject approach we use in CoreUI Vue components for theme and configuration management. Use descriptive keys and provide default values in inject to handle missing providers gracefully.



