JAVASCRIPT
Vue 3 Global State Management with Pinia Store
Learn to implement global state management in Vue 3 applications using Pinia, Vue's official store library, for reactive and organized data flow.
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Vue Dev'
}),
getters: {
doubleCount: (state) => state.count * 2,
greeting: (state) => `Hello, ${state.name}! Your count is ${state.count}`
},
actions: {
increment() {
this.count++;
},
reset() {
this.count = 0;
}
}
});
// App.vue (or any component)
<template>
<div>
<h1>{{ counter.greeting }}</h1>
<p>Current Count: {{ counter.count }}</p>
<p>Double Count: {{ counter.doubleCount }}</p>
<button @click="counter.increment()">Increment</button>
<button @click="counter.reset()">Reset</button>
</div>
</template>
<script setup>
import { useCounterStore } from './stores/counter';
const counter = useCounterStore();
// You can also destructure actions and state directly if needed,
// but remember to use storeToRefs for reactive state properties.
// import { storeToRefs } from 'pinia';
// const { count, doubleCount } = storeToRefs(counter);
// const { increment, reset } = counter;
</script>
How it works: This snippet demonstrates how to set up a Pinia store for global state management in Vue 3. It defines a store with `state` for reactive data, `getters` for derived state, and `actions` for modifying state. In a component, `useCounterStore()` hooks into the store, allowing reactive access to state properties and invocation of actions. Pinia is Vue's recommended state management solution, offering a simple and type-safe approach.