JAVASCRIPT
Vue 3 Pinia State Management: Basic Store Setup and Usage
Learn to set up and interact with a basic Pinia store in Vue 3 for centralized state management, enabling efficient data sharing across components.
// main.js or main.ts
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');
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Eduardo'
}),
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;
}
}
});
// components/MyComponent.vue
<template>
<div>
<h2>Counter (Pinia)</h2>
<p>Count: {{ counterStore.count }}</p>
<p>Double Count: {{ counterStore.doubleCount }}</p>
<p>{{ counterStore.greeting }}</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';
const counterStore = useCounterStore();
// You can also destructure state and actions, but be mindful of reactivity for state
// import { storeToRefs } from 'pinia';
// const { count, doubleCount } = storeToRefs(counterStore); // maintains reactivity for state
// const { increment, reset } = counterStore; // actions can be destructured directly
</script>
How it works: This snippet illustrates how to implement basic state management using Pinia, the recommended state library for Vue 3. It shows how to define a store with `state`, `getters`, and `actions`, and then how to consume that store within a Vue component using the `useCounterStore()` hook. Pinia simplifies state management, making it reactive and shareable across any component in your application.