JAVASCRIPT
Sharing State Across Components with Provide/Inject in Vue 3
Learn how to effectively share reactive state or utilities across deeply nested components in Vue 3 using the `provide` and `inject` API, avoiding prop drilling.
// src/components/ParentComponent.vue
<template>
<div class="parent-component">
<h1>Parent Component</h1>
<button @click="incrementCount">Increment from Parent</button>
<ChildComponent />
</div>
</template>
<script setup>
import { provide, ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const sharedCount = ref(0);
const incrementCount = () => {
sharedCount.value++;
};
provide('appCount', sharedCount); // Provide the reactive ref
provide('incrementAppCount', incrementCount); // Provide a method too
</script>
<style scoped>
.parent-component { border: 1px solid blue; padding: 20px; margin: 10px; }
</style>
// src/components/ChildComponent.vue
<template>
<div class="child-component">
<h2>Child Component</h2>
<GrandchildComponent />
</div>
</template>
<script setup>
import GrandchildComponent from './GrandchildComponent.vue';
</script>
<style scoped>
.child-component { border: 1px solid green; padding: 15px; margin: 10px; }
</style>
// src/components/GrandchildComponent.vue
<template>
<div class="grandchild-component">
<h3>Grandchild Component</h3>
<p>Shared Count: {{ injectedCount }}</p>
<button @click="injectedIncrement">Increment from Grandchild</button>
</div>
</template>
<script setup>
import { inject } from 'vue';
const injectedCount = inject('appCount');
const injectedIncrement = inject('incrementAppCount');
</script>
<style scoped>
.grandchild-component { border: 1px solid red; padding: 10px; margin: 10px; }
</style>
How it works: This snippet demonstrates Vue 3's `provide` and `inject` API for passing data down a component tree without prop drilling. A `ParentComponent` provides a reactive `ref` (`sharedCount`) and a method (`incrementCount`). `GrandchildComponent`, nested deeper, can directly `inject` and utilize these provided values, allowing for flexible state management or utility sharing across components.