JAVASCRIPT
Basic Global State Management with Pinia in Vue 3
Implement robust global state management in your Vue 3 applications using Pinia, the intuitive and lightweight store library, for centralized data handling.
// stores/counter.js (Pinia store definition)
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
export const useCounterStore = defineStore('counter', () => {
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value++;
}
function decrement() {
count.value--;
}
return { count, doubleCount, increment, decrement };
});
// main.js (Pinia setup in main application file)
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
app.use(createPinia()); // Install Pinia
app.mount('#app');
// CounterComponent.vue (Component consuming the Pinia store)
<template>
<div>
<h1>Pinia Counter</h1>
<p>Count: {{ counter.count }}</p>
<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: This snippet demonstrates the basic setup and usage of Pinia, the recommended state management library for Vue 3. It shows how to define a store using `defineStore`, leveraging Composition API `ref`s and `computed` properties for state and getters, and functions for actions. The store is then installed into the Vue application in `main.js` and consumed by any component using `useCounterStore()`, providing a centralized and reactive way to manage global application state.