JAVASCRIPT
Simple Global State Management with Vue 3 Provide/Inject
Learn to manage global application state effectively in Vue 3 using the Composition API's `provide` and `inject` functions for dependency injection across components.
// src/store/counter.js
import { ref, readonly } from 'vue';
export const counterKey = Symbol();
export function useCounterStore() {
const count = ref(0);
function increment() {
count.value++;
}
function decrement() {
count.value--;
}
return { count: readonly(count), increment, decrement };
}
// src/App.vue (Provider)
<template>
<div>
<h1>Counter Provider</h1>
<ChildComponent />
</div>
</template>
<script setup>
import { provide } from 'vue';
import ChildComponent from './components/ChildComponent.vue';
import { useCounterStore, counterKey } from './store/counter';
const counterStore = useCounterStore();
provide(counterKey, counterStore);
</script>
// src/components/ChildComponent.vue (Consumer)
<template>
<div style="border: 1px solid #ccc; padding: 10px; margin: 10px;">
<h2>Child Component</h2>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>
</template>
<script setup>
import { inject } from 'vue';
import { counterKey } from '../store/counter';
const { count, increment, decrement } = inject(counterKey);
</script>
How it works: This snippet demonstrates how to create a simple global state store using Vue 3's Composition API and `provide`/`inject`. The `useCounterStore` composable manages a `count` ref and its mutations. In `App.vue`, this store is `provide`d to all descendants using a `Symbol` as a key. Any descendant component, like `ChildComponent.vue`, can then `inject` this store using the same key to access the shared state and its methods, ensuring reactivity and easy state management across the component tree without prop drilling.