JAVASCRIPT
Global State Management with Pinia Store
Implement a global state management system in Vue 3 using Pinia, Vue's recommended store, for managing user data across your application.
// stores/userStore.js
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
state: () => ({
username: 'Guest',
isAuthenticated: false,
token: null,
}),
getters: {
welcomeMessage: (state) => `Welcome, ${state.username}!`,
},
actions: {
login(newUsername, newToken) {
this.username = newUsername;
this.token = newToken;
this.isAuthenticated = true;
},
logout() {
this.username = 'Guest';
this.token = null;
this.isAuthenticated = false;
},
},
});
// How to use in a component (e.g., App.vue):
// <script setup>
// import { useUserStore } from './stores/userStore';
// import { storeToRefs } from 'pinia';
//
// const userStore = useUserStore();
//
// // To destructure reactive state from the store while maintaining reactivity:
// const { username, isAuthenticated, welcomeMessage } = storeToRefs(userStore);
//
// // Actions can be called directly
// function handleLogin() {
// userStore.login('JohnDoe', 'some-jwt-token');
// }
// function handleLogout() {
// userStore.logout();
// }
// </script>
//
// <template>
// <div>
// <p>{{ welcomeMessage }}</p>
// <button v-if="!isAuthenticated" @click="handleLogin">Login</button>
// <button v-else @click="handleLogout">Logout</button>
// </div>
// </template>
How it works: This snippet demonstrates how to set up a global state store using Pinia, the recommended state management library for Vue 3. It defines a `userStore` with reactive `state` (username, authentication status), `getters` (derived state like `welcomeMessage`), and `actions` (methods to mutate state). In a component, `useUserStore()` provides access to the store. `storeToRefs` is used to extract reactive properties from the store's state, while actions are called directly, simplifying global state management.