JAVASCRIPT
Building a Simple Reactive Global State Store in Vue 3
Implement a basic global state management solution in Vue 3 using the reactivity API (`reactive`) for sharing data across components without a dedicated library.
// store/index.js
import { reactive, readonly } from 'vue';
const state = reactive({
user: {
name: 'Guest User',
isLoggedIn: false,
theme: 'light'
},
settings: {
notificationsEnabled: true,
language: 'en'
}
});
const actions = {
login(username) {
state.user.name = username;
state.user.isLoggedIn = true;
},
logout() {
state.user.name = 'Guest User';
state.user.isLoggedIn = false;
},
toggleTheme() {
state.user.theme = state.user.theme === 'light' ? 'dark' : 'light';
},
toggleNotifications() {
state.settings.notificationsEnabled = !state.settings.notificationsEnabled;
}
};
export const store = {
state: readonly(state), // Prevent direct modification from components
...actions // Expose actions for mutation
};
// Usage in a Vue component (e.g., App.vue or a child component):
/*
<template>
<div>
<h1>Welcome, {{ store.state.user.name }}!</h1>
<p>Theme: {{ store.state.user.theme }}</p>
<button v-if="!store.state.user.isLoggedIn" @click="store.login('John Doe')">Login</button>
<button v-else @click="store.logout()">Logout</button>
<button @click="store.toggleTheme()">Toggle Theme</button>
</div>
</template>
<script setup>
import { store } from './store'; // Adjust path as needed
</script>
*/
How it works: This snippet demonstrates how to create a minimalist global state store in Vue 3 using the `reactive` and `readonly` APIs. The `state` object holds the application's global data, and `actions` are functions that modify this state. By exposing `state` as `readonly`, components can safely access data without accidentally modifying it, enforcing state changes through defined actions. This pattern provides a simple, reactive solution for sharing data across multiple components without the overhead of full-fledged state management libraries for simpler use cases.