JAVASCRIPT

Simple Global Store Composable for Vue 3

Create a reactive global state management system in Vue 3 using the Composition API, offering a lightweight alternative to Vuex or Pinia for smaller applications.

// store/auth.js
import { ref, readonly } from 'vue';

const user = ref(null);
const isAuthenticated = ref(false);

function setUser(userData) {
  user.value = userData;
  isAuthenticated.value = !!userData;
}

function logout() {
  user.value = null;
  isAuthenticated.value = false;
}

export function useAuthStore() {
  return {
    user: readonly(user),
    isAuthenticated: readonly(isAuthenticated),
    setUser,
    logout,
  };
}

// src/App.vue
<template>
  <div>
    <div v-if="auth.isAuthenticated">
      Welcome, {{ auth.user?.name }}!
      <button @click="auth.logout()">Logout</button>
    </div>
    <div v-else>
      <p>Please log in.</p>
      <button @click="loginMockUser()">Login</button>
    </div>
  </div>
</template>

<script setup>
import { useAuthStore } from './store/auth';

const auth = useAuthStore();

const loginMockUser = () => {
  // Simulate a login API call
  setTimeout(() => {
    auth.setUser({ id: 1, name: 'John Doe', email: '[email protected]' });
  }, 500);
};
</script>
How it works: This snippet demonstrates how to build a simple, reactive global store using Vue 3's Composition API. The `useAuthStore` composable encapsulates authentication logic and state (`user`, `isAuthenticated`). `ref` creates reactive state, and `readonly` ensures direct modification of state is prevented outside the store, promoting predictable state changes through defined actions like `setUser` and `logout`. Components consume the store by calling `useAuthStore()`, gaining access to its reactive state and methods.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs