Provide and Inject
Provide and inject share data down a component tree without passing props at each step. A parent provides a value, and any descendant injects it.
Provide the value
The parent shares dark under the key theme.
provide('theme', 'dark')Inject the value
The child reads the value back by the same key.
const theme = inject('theme')The child on the page
The child shows the injected theme.
<Child />Example
<script setup>
import { defineComponent, provide, inject } from 'vue'
const Child = defineComponent({
setup() {
const theme = inject('theme')
return { theme }
},
template: `<p>Theme: {{ theme }}</p>`
})
provide('theme', 'dark')
</script>
<template>
<div>
<Child />
</div>
</template>
Key points
- provide shares a value under a key, like the string theme.
- A key is the name a value is stored under.
- inject reads the value back by the same key.
- Any descendant can inject the value, no matter how deep it sits.
- Use props for one direct child, and provide for many levels down.
- The provided value can be a ref, so descendants see updates.
In this example, the parent calls provide with the key theme and the value dark. Child is a small component in the same file. Its setup calls inject with the key theme and returns the value. The template shows Theme dark. The value passes straight to the child with no prop at any step.
Note
Import provide and inject from vue before calling them.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does inject do?