JAVASCRIPT
Manage Global State with Vue 3 Pinia Store
Discover how to use Pinia, the official state management library for Vue 3, to create a simple store for managing global application state efficiently and reactively in your projects.
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
getters: {
doubleCount: (state) => state.count * 2
},
actions: {
increment(amount = 1) {
this.count += amount;
},
decrement(amount = 1) {
this.count -= amount;
}
}
});
// App.vue (example usage)
<template>
<div>
<h1>Count: {{ counterStore.count }}</h1>
<h2>Double Count: {{ counterStore.doubleCount }}</h2>
<button @click="counterStore.increment()">Increment</button>
<button @click="counterStore.increment(5)">Increment by 5</button>
<button @click="counterStore.decrement()">Decrement</button>
</div>
</template>
<script setup>
import { useCounterStore } from './stores/counter';
const counterStore = useCounterStore();
</script>
How it works: This example shows how to set up a basic Pinia store. `defineStore` creates a store named 'counter' with a `state` (reactive data), `getters` (computed properties for state), and `actions` (methods to modify state). In `App.vue`, `useCounterStore()` is called to access the store, allowing components to read and modify the global state reactively, providing a scalable solution for state management.