JAVASCRIPT
Centralized State Management with Pinia
Learn how to set up and use Pinia, the intuitive and type-safe state management library for Vue 3 applications, to manage global application state efficiently.
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Pinia User',
}),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment(amount = 1) {
this.count += amount;
},
reset() {
this.count = 0;
},
},
});
// main.js (or wherever you initialize Vue app)
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');
// SomeComponent.vue
<script setup>
import { useCounterStore } from './stores/counter';
import { storeToRefs } from 'pinia'; // Optional for destructuring state with reactivity
const counter = useCounterStore();
// Access state directly
console.log(counter.count);
// Update state
counter.increment();
// Access getters
console.log(counter.doubleCount);
// Destructure state properties while keeping reactivity
const { count, name } = storeToRefs(counter);
</script>
<template>
<div>
<p>Count: {{ counter.count }}</p>
<p>Double Count: {{ counter.doubleCount }}</p>
<p>User Name: {{ name }}</p>
<button @click="counter.increment()">Increment</button>
<button @click="counter.reset()">Reset</button>
</div>
</template>
How it works: This snippet demonstrates how to set up and use Pinia for centralized state management in Vue 3. It defines a store with state, getters, and actions, then initializes Pinia in the main application file. Components can then import and use the store to access reactive state, computed getters, and dispatch actions, optionally using `storeToRefs` to destructure state properties while maintaining reactivity.