JAVASCRIPT
Vue 3 Pinia Store Setup and Usage
Learn to set up and utilize Pinia, the modern and recommended state management library for Vue 3, to centralize and efficiently manage application data across components.
// stores/counter.js
import { defineStore } from 'pinia';
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() {
this.count++;
},
decrement() {
this.count--;
},
async fetchAndSetCount() {
// Simulate an async operation
const response = await new Promise(resolve => setTimeout(() => resolve(100), 500));
this.count = response;
}
}
});
// main.js (or any component 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');
// components/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.fetchAndSetCount">Fetch & Set Count</button>
</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 Vue 3. It defines a `counter` store with state, getters, and actions. The `main.js` file initializes Pinia and makes it available to the Vue application. In `MyComponent.vue`, the `useCounterStore` hook is used to access the store's state, getters, and actions, allowing components to read and modify global application state reactively.