Provide and Inject


🧩 What are provide and inject?

provide and inject are Vue features that let you share data or functions between a parent component and its descendant components — without having to pass props through every intermediate level.

Think of it like a “context system”, similar to React’s Context API.


⚙️ Basic Example

🟢 Parent Component (Parent.vue)

<template>
  <div>
    <h2>Parent</h2>
    <Child />
  </div>
</template>

<script setup>
import { ref, provide } from 'vue'
import Child from './Child.vue'

const message = ref('Hello from Parent!')

// Make this value available to all descendants
provide('message', message)
</script>

🟣 Deep Child Component (Child.vue)

<template>
  <div>
    <p>Injected: {{ message }}</p>
  </div>
</template>

<script setup>
import { inject } from 'vue'

// Access provided value using the same key
const message = inject('message')
</script>

✅ Output:

Injected: Hello from Parent!

🔁 Reactivity Notes

If the provided value is reactive (ref or reactive),
the injected value stays reactive — changes in the parent update the child automatically.

Example:

// parent
const count = ref(0)
provide('count', count)

// child
const count = inject('count')

// child template
<button @click="count.value++">Increment: {{ count }}</button>

Both parent and child see the updated count.


🧠 With Default Value

If the ancestor doesn’t call provide, you can give a default:

const theme = inject('theme', 'light')

If no provider exists, theme will be 'light'.


🧰 Common Use Cases

Use CaseExample
App-wide configurationProvide app settings, inject in many components
Dependency injectionProvide an API client or service
ThemingProvide a theme or color scheme
User contextProvide user data to deeply nested components

🧱 Provide/Inject Flow Diagram

App.vue (provide)

Layout.vue

Sidebar.vue

SidebarItem.vue (inject)

You only provide once at the top, and any descendant can inject directly.


⚖️ Summary Table

FeatureDescription
provide(key, value)Makes value available to descendants
inject(key, default?)Accesses the provided value
Works with Composition APIYes (setup or <script setup>)
Reactive?Yes, if provided value is reactive
ScopeParent → Descendants only

Leave a Reply