JAVASCRIPT
Implement Global State Management with Pinia
Efficiently manage application-wide state in Vue 3 using Pinia, Vue's official store library, for predictable and scalable data flow across components.
// store/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Vue User'
}),
getters: {
doubleCount: (state) => state.count * 2,
greeting: (state) => `Hello, ${state.name}! Your count is ${state.count}`
},
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
setCount(amount) {
this.count = amount;
}
}
});
// main.js (or a setup file)
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount('#app');
// MyComponent.vue
<template>
<div>
<p>{{ counterStore.greeting }}</p>
<p>Count: {{ counterStore.count }}</p>
<p>Double Count: {{ counterStore.doubleCount }}</p>
<button @click="counterStore.increment()">Increment</button>
<button @click="counterStore.decrement()">Decrement</button>
<button @click="counterStore.setCount(10)">Set to 10</button>
</div>
</template>
<script setup>
import { useCounterStore } from './store/counter';
const counterStore = useCounterStore();
</script>
How it works: This snippet demonstrates how to set up and use Pinia, the recommended state management library for Vue 3. It defines a store with reactive state, computed getters, and methods (actions) to modify the state. The store is then registered globally with the Vue application and can be easily accessed and manipulated within any component using the `useCounterStore()` hook from the `setup` script, providing a centralized and organized way to manage application data.