Dependency injection helps you share data or functions between components without passing them through many layers. It makes your code cleaner and easier to manage.
0
0
Dependency injection patterns in Vue
Introduction
You want to share a service or data across many components without passing props repeatedly.
You have a theme or configuration that many parts of your app need to access.
You want to provide a function or object once and let child components use it directly.
You want to avoid tightly coupling components by passing dependencies explicitly.
You want to make testing easier by swapping dependencies.
Syntax
Vue
import { provide, inject } from 'vue' // In a parent or ancestor component provide('keyName', value) // In a child or descendant component const value = inject('keyName')
provide sets a value that descendants can access.
inject lets a component receive that value by the same key.
Examples
This parent component shares the string 'blue' with its descendants under the key 'color'.
Vue
import { provide } from 'vue' export default { setup() { provide('color', 'blue') } }
This child component receives the 'color' value provided by an ancestor.
Vue
import { inject } from 'vue' export default { setup() { const color = inject('color') return { color } } }
Sharing an object like a user info between components.
Vue
import { provide, inject } from 'vue' // Parent export default { setup() { const user = { name: 'Alice' } provide('user', user) } } // Child export default { setup() { const user = inject('user') return { user } } }
Sample Program
The parent component provides a theme object with color and font size. The child component injects this theme and uses it to style its text.
Vue
<template>
<div>
<h2>Parent Component</h2>
<ChildComponent />
</div>
</template>
<script setup>
import { provide } from 'vue'
import ChildComponent from './ChildComponent.vue'
const theme = { color: 'teal', fontSize: '1.2rem' }
provide('theme', theme)
</script>
<!-- ChildComponent.vue -->
<template>
<div :style="{ color: theme.color, fontSize: theme.fontSize }">
This text uses the injected theme.
</div>
</template>
<script setup>
import { inject } from 'vue'
const theme = inject('theme')
</script>OutputSuccess
Important Notes
If the injected key is not found, inject returns undefined unless you provide a default value.
You can provide default values like inject('key', defaultValue) to avoid errors.
Dependency injection works only between ancestor and descendant components, not siblings.
Summary
Dependency injection shares data or functions between components without prop drilling.
Use provide in an ancestor and inject in descendants.
This pattern keeps your code clean and easier to maintain.