JAVASCRIPT
State Management with Pinia Store in Vue 3
Learn to implement robust state management in Vue 3 applications using Pinia. Define state, getters, and actions for a global data store.
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0, name: 'Eduardo' }),
getters: {
doubleCount: (state) => state.count * 2,
getName: (state) => `Hello, my name is ${state.name}`,
},
actions: {
increment() {
this.count++;
},
incrementBy(amount) {
this.count += amount;
},
},
});
// main.js (Vue app setup)
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');
// AnyComponent.vue
<template>
<div>
<p>Count: {{ counter.count }}</p>
<p>Double Count: {{ counter.doubleCount }}</p>
<p>{{ counter.getName }}</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();
</script>
How it works: This snippet demonstrates how to set up and use Pinia, the recommended state management library for Vue 3. It shows how to define a store with reactive state, computed getters to derive new state, and actions to modify the state. The Pinia store is then integrated into the Vue application in `main.js`, making it accessible to any component. In a component, the `useCounterStore` hook is used to access the store's state, getters, and actions, allowing for simple global state manipulation.