JAVASCRIPT
Implementing Centralized State Management with Pinia in Vue 3
Learn to set up and use Pinia, the recommended state management library for Vue 3, to manage application-wide data efficiently and reactively across components.
// src/stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0, name: 'Eduardo' }),
getters: {
doubleCount: (state) => state.count * 2,
greeting: (state) => `Hello, ${state.name}! Count is ${state.count}`
},
actions: {
increment() {
this.count++;
},
incrementBy(amount) {
this.count += amount;
}
}
});
// src/App.vue
<template>
<div>
<h1>Pinia Counter</h1>
<p>Count: {{ counter.count }}</p>
<p>Double Count: {{ counter.doubleCount }}</p>
<p>{{ counter.greeting }}</p>
<button @click="counter.increment()">Increment</button>
<button @click="counter.incrementBy(5)">Increment by 5</button>
</div>
</template>
<script setup>
import { useCounterStore } from './stores/counter';
const counter = useCounterStore();
// You can also access state and actions directly
// const { count, doubleCount } = storeToRefs(counter);
// const { increment, incrementBy } = counter;
</script>
How it works: This snippet demonstrates how to set up a basic Pinia store in Vue 3 for centralized state management. It defines a `counter` store with reactive `state`, `getters` for derived state, and `actions` for modifying the state. The `App.vue` component then imports and uses the store, accessing its state, getters, and calling its actions directly through the `useCounterStore()` hook. Pinia provides a simple, type-safe, and modular way to manage application state.