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.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to loop inside React JSX
How to loop inside React JSX

How to Open All Links in New Tab Using JavaScript
How to Open All Links in New Tab Using JavaScript

How to return multiple values from a JavaScript function
How to return multiple values from a JavaScript function

How to Hide Scrollbar with CSS
How to Hide Scrollbar with CSS

Answers by CoreUI Core Team