JAVASCRIPT
Global State Sharing in Vue 3 with Provide and Inject
Discover how to use Vue 3's `provide` and `inject` to efficiently share data and functions down a component hierarchy, bypassing prop drilling and simplifying state management in deeply nested components.
// ParentComponent.vue
<template>
<div>
<h1>Parent Component</h1>
<p>Shared Message: {{ sharedMessage }}</p>
<button @click="changeMessage">Change Shared Message</button>
<ChildComponent />
</div>
</template>
<script setup>
import { ref, provide } from 'vue';
import ChildComponent from './ChildComponent.vue';
const sharedMessage = ref('Hello from Parent!');
const changeMessage = () => {
sharedMessage.value = 'Message changed at ' + new Date().toLocaleTimeString();
};
// Provide a reactive value and a function
provide('appMessage', sharedMessage);
provide('updateMessage', changeMessage);
</script>
// ChildComponent.vue
<template>
<div style="border: 1px solid blue; padding: 10px; margin-top: 10px;">
<h2>Child Component</h2>
<p>Injected Message: {{ appMessage }}</p>
<button @click="updateMessage">Update Message from Child</button>
<GrandchildComponent />
</div>
</template>
<script setup>
import { inject } from 'vue';
import GrandchildComponent from './GrandchildComponent.vue';
// Inject the provided values
const appMessage = inject('appMessage');
const updateMessage = inject('updateMessage');
</script>
// GrandchildComponent.vue
<template>
<div style="border: 1px solid green; padding: 5px; margin-top: 5px;">
<h3>Grandchild Component</h3>
<p>Injected Message: {{ appMessage }}</p>
</div>
</template>
<script setup>
import { inject } from 'vue';
// Inject the provided value
const appMessage = inject('appMessage');
</script>
How it works: This example illustrates how `provide` and `inject` facilitate global state sharing across a component tree in Vue 3. A parent component `provides` a reactive `ref` (`sharedMessage`) and a function (`changeMessage`) using unique keys. Child and grandchild components can then `inject` these values, making them accessible without explicitly passing props down through every intermediate component. This pattern is ideal for common application-wide data or utilities, preventing "prop drilling."