JAVASCRIPT
Implementing a Pinia Store for Global State Management
Learn how to effectively manage global application state in Vue 3 using Pinia, the lightweight and intuitive state management library, with an example store setup and component usage.
import { defineStore } from 'pinia';
// 1. Define your Pinia store
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Vue User'
}),
getters: {
doubleCount: (state) => state.count * 2,
greeting: (state) => `Hello, ${state.name}! Your count is ${state.count}.`
},
actions: {
increment(amount = 1) {
this.count += amount;
},
reset() {
this.count = 0;
}
}
});
// 2. Use the store in a Vue 3 component
// In your main.js or similar entry point, make sure Pinia is installed:
// import { createApp } from 'vue';
// import { createPinia } from 'pinia';
// import App from './App.vue';
// const app = createApp(App);
// app.use(createPinia());
// app.mount('#app');
// Example component usage:
/*
<template>
<div>
<h1>{{ counterStore.greeting }}</h1>
<p>Count: {{ counterStore.count }}</p>
<p>Double Count: {{ counterStore.doubleCount }}</p>
<button @click="counterStore.increment()">Increment</button>
<button @click="counterStore.increment(5)">Increment by 5</button>
<button @click="counterStore.reset()">Reset</button>
</div>
</template>
<script setup>
import { useCounterStore } from './stores/counter'; // Adjust path as needed
const counterStore = useCounterStore();
// You can also destructure state and getters for reactivity
// import { storeToRefs } from 'pinia';
// const { count, doubleCount } = storeToRefs(counterStore);
// const { increment, reset } = counterStore;
</script>
*/
How it works: This snippet demonstrates how to set up and use Pinia for state management in a Vue 3 application. It defines a `counter` store with `state` (reactive data), `getters` (computed properties derived from state), and `actions` (methods to modify state). The component example shows how to import the store using `useCounterStore()` and interact with its state, getters, and actions directly from the template and script setup, providing a clear and efficient way to manage global application data.