JAVASCRIPT
Vue 3 Global State Management with Pinia
Learn how to set up and use Pinia, the official state management library for Vue 3, to manage global application state efficiently and reactively across components.
// src/stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Pinia User'
}),
getters: {
doubleCount: (state) => state.count * 2,
greeting: (state) => `Hello, ${state.name}! Your count is ${state.count}.`,
},
actions: {
increment() {
this.count++;
},
incrementBy(amount) {
this.count += amount;
},
reset() {
this.count = 0;
}
},
});
// src/App.vue
<template>
<div>
<h1>Pinia Counter Example</h1>
<p>Count: {{ counterStore.count }}</p>
<p>Double Count: {{ counterStore.doubleCount }}</p>
<p>{{ counterStore.greeting }}</p>
<button @click="counterStore.increment()">Increment</button>
<button @click="counterStore.incrementBy(5)">Increment by 5</button>
<button @click="counterStore.reset()">Reset</button>
<input v-model="counterStore.name" placeholder="Enter name" />
</div>
</template>
<script setup>
import { useCounterStore } from './stores/counter';
const counterStore = useCounterStore();
</script>
How it works: This snippet demonstrates how to define a Pinia store (`counter.js`) with state, getters, and actions. The `App.vue` component then imports and uses this store to access and modify the global state reactively. Pinia simplifies state management, making it type-safe and modular for larger Vue 3 applications.