What is Provide and Inject in Vue: Simple Explanation and Example
provide and inject in Vue are a pair of features that let a parent component share data or functions with its descendants without passing props through every level. provide sets the data at a higher level, and inject allows child components to access it directly, simplifying communication in deep component trees.How It Works
Imagine you have a family tree where the grandparent wants to give a gift to the grandchild, but there are parents and children in between. Instead of handing the gift through each person, the grandparent just leaves it in a special place, and the grandchild can pick it up directly. In Vue, provide is like the grandparent leaving the gift, and inject is the grandchild picking it up.
This means a parent component can "provide" some data or functions, and any nested child component can "inject" and use them without the need to pass props step-by-step. This helps keep your code cleaner and avoids prop drilling when many layers separate components.
Example
This example shows a parent component providing a message, and a nested child component injecting and displaying it.
import { defineComponent, provide, inject } from 'vue'; const Child = defineComponent({ setup() { const message = inject('message'); return { message }; }, template: `<p>Injected message: {{ message }}</p>` }); export default defineComponent({ components: { Child }, setup() { provide('message', 'Hello from parent!'); }, template: `<div><h2>Parent Component</h2><Child /></div>` });
When to Use
Use provide and inject when you want to share data or functions deeply in your component tree without passing props through many layers. This is helpful for things like theme settings, user info, or global services.
For example, if you have a theme color set in a top-level component and many nested components need to know it, provide can share it once, and all children can inject it directly. This avoids cluttering intermediate components with props they don't use.
Key Points
- Provide shares data or functions from a parent component.
- Inject accesses that data in any descendant component.
- They help avoid prop drilling in deep component trees.
- Injected values are not reactive by default unless you provide reactive objects.
- Useful for global-like data such as themes, user info, or services.