JAVASCRIPT
Centralized State Management with Pinia in Vue 3
Learn to set up and use Pinia, the intuitive state management library for Vue 3, to manage application-wide data efficiently and reactively across components.
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'VueMaster'
}),
getters: {
doubleCount: (state) => state.count * 2,
greeting: (state) => `Hello, ${state.name}! Your count is ${state.count}.`
},
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
reset() {
this.count = 0;
}
}
});
// main.js (or plugin 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');
// MyComponent.vue
<template>
<div>
<h1>{{ counter.greeting }}</h1>
<p>Count: {{ counter.count }}</p>
<p>Double Count: {{ counter.doubleCount }}</p>
<button @click="counter.increment">Increment</button>
<button @click="counter.decrement">Decrement</button>
<button @click="counter.reset">Reset</button>
<input v-model="counter.name" placeholder="Enter your name" />
</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 for state management in a Vue 3 application. It defines a `counter` store with reactive state, computed getters (`doubleCount`, `greeting`), and actions (`increment`, `decrement`, `reset`) to modify the state. The store is then registered globally in `main.js`. In `MyComponent.vue`, the `useCounterStore` hook provides access to the store's state, getters, and actions, allowing components to read and modify application-wide data efficiently.