JAVASCRIPT
Global State Management with Pinia in Vue 3
Learn how to effectively manage global application state in Vue 3 using Pinia, Vue's lightweight and intuitive state management library, ensuring reactive data flows across components.
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Eduardo',
}),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
this.count++;
},
async incrementAndLoadUser(userId) {
this.increment();
// Simulate API call
// const user = await fetchUserApi(userId);
// this.name = user.name;
},
},
});
// App.vue (or any component)
<template>
<div>
<p>Count: {{ counter.count }}</p>
<p>Double Count: {{ counter.doubleCount }}</p>
<button @click="counter.increment()">Increment</button>
<p>User Name: {{ counter.name }}</p>
</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 a Pinia store for global state management in a Vue 3 application. It defines a `counter` store with a state, a getter (`doubleCount`) for computed state, and actions (`increment`, `incrementAndLoadUser`) to modify the state. Components can easily access and react to changes in this global state by importing and instantiating the store, providing a clean and maintainable way to share data across your application.