JAVASCRIPT
Managing Global State with Vue 3 Provide/Inject
Discover how to use Vue 3's `provide` and `inject` to manage global state across deeply nested components without prop drilling, enhancing component communication.
// App.vue (Parent component)
<template>
<div>
<h1>App Component</h1>
<button @click="toggleMessage">Toggle Message</button>
<ChildComponent />
</div>
</template>
<script setup>
import { ref, provide } from 'vue';
import ChildComponent from './components/ChildComponent.vue';
const sharedMessage = ref('Hello from App!');
const toggleMessage = () => {
sharedMessage.value = sharedMessage.value === 'Hello from App!' ? 'Goodbye from App!' : 'Hello from App!';
};
// Provide the message and a method to update it
provide('myGlobalMessage', sharedMessage);
provide('toggleGlobalMessage', toggleMessage);
</script>
// components/ChildComponent.vue (Intermediate component, could be many levels deep)
<template>
<div style="border: 1px solid blue; padding: 10px; margin: 10px;">
<h2>Child Component</h2>
<GrandchildComponent />
</div>
</template>
<script setup>
import GrandchildComponent from './GrandchildComponent.vue';
// ChildComponent doesn't need to know about the message
</script>
// components/GrandchildComponent.vue (Deeply nested component)
<template>
<div style="border: 1px solid green; padding: 10px; margin: 10px;">
<h3>Grandchild Component</h3>
<p>Global Message: {{ injectedMessage }}</p>
<button @click="injectedToggle">Toggle Global Message from Grandchild</button>
</div>
</template>
<script setup>
import { inject } from 'vue';
// Inject the provided values
const injectedMessage = inject('myGlobalMessage');
const injectedToggle = inject('toggleGlobalMessage');
</script>
How it works: This example illustrates `provide` and `inject` in Vue 3 for passing data and functions down a component tree without explicit prop drilling. The `App.vue` component `provide`s `sharedMessage` and `toggleMessage`, which can then be `inject`ed by any descendant component, like `GrandchildComponent.vue`, regardless of how many intermediate components lie between them. This simplifies state management for shared data.