JAVASCRIPT
Implement Global State Management with Pinia in Vue 3
Learn how to set up and use Pinia, the recommended state management library for Vue 3, to centralize application state and share data across components efficiently.
// src/stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Vue Dev'
}),
getters: {
doubleCount: (state) => state.count * 2,
greeting: (state) => `Hello, ${state.name}!`
},
actions: {
increment() {
this.count++;
},
incrementBy(amount) {
this.count += amount;
}
}
});
// src/main.js (or wherever you initialize your app)
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
app.use(createPinia());
app.mount('#app');
// src/components/CounterDisplay.vue
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double Count: {{ doubleCount }}</p>
<p>{{ greeting }}</p>
<button @click="increment">Increment</button>
<button @click="incrementBy(5)">Increment by 5</button>
</div>
</template>
<script setup>
import { useCounterStore } from '../stores/counter';
import { storeToRefs } from 'pinia';
const counterStore = useCounterStore();
const { count, doubleCount, greeting } = storeToRefs(counterStore); // Use storeToRefs to maintain reactivity
const { increment, incrementBy } = counterStore; // Actions can be destructured directly
</script>
How it works: This snippet demonstrates setting up Pinia for global state management in a Vue 3 application. It defines a store with `state`, `getters`, and `actions`, then initializes Pinia in `main.js`. In a component, `useCounterStore()` accesses the store, `storeToRefs()` extracts reactive state and getters, while actions can be called directly. This centralizes state, making it easily accessible and modifiable across components.