JAVASCRIPT
Managing Global State with Pinia in Vue 3
Master global state management in Vue 3 using Pinia, a lightweight and intuitive store for application-wide data, enhancing reactivity and developer experience.
// src/stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
},
});
// src/main.js (for Pinia 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');
// src/components/PiniaCounter.vue
<template>
<div>
<h2>Pinia Counter: {{ counter.count }}</h2>
<p>Double Count: {{ counter.doubleCount }}</p>
<button @click="counter.increment">Increment</button>
<button @click="counter.decrement">Decrement</button>
</div>
</template>
<script setup>
import { useCounterStore } from '@/stores/counter';
const counter = useCounterStore();
</script>
How it works: Pinia is the recommended state management solution for Vue 3. This snippet illustrates defining a Pinia store (`useCounterStore`) with reactive `state`, `getters` for computed state, and `actions` for modifying state. After setting up Pinia in `main.js`, components can easily access and manipulate the global state by importing and using the store, providing a centralized and predictable way to manage application data.