1. Understand the Goal: The user wants a Vue 3 application design using Pinia for "modular state management." This means I shouldn't just put everything in one store. I need to demonstrate how to split concerns (e.g., user auth, product list, cart) into separate stores and how they interact within a Vue 3 app.
-
Key Technologies:
- Vue 3 (Composition API is the standard/modern choice).
- Pinia (The official state management library).
- Vite (Standard build tool).
- TypeScript (Good practice for "designing" an app, though JS is fine, TS adds structure. I'll stick to JS/standard syntax but keep it clean so it's easily adaptable). Self-correction: Stick to standard JavaScript for broader accessibility, but mention structure.
-
Architecture/Structure:
- Entry Point:
main.js (initializing Pinia).
- Store Directory:
src/stores/.
- Modules: I need at least two distinct stores to demonstrate "modular" design.
useUserStore: Handles authentication, profile data.
useCartStore: Handles items, totals, checkout logic. (This is a classic example).
- Components: Views that consume these stores.
UserProfile.vue (uses UserStore).
ShoppingCart.vue (uses CartStore).
App.vue (Brings it together).
-
Step-by-Step Implementation Plan:
- Prerequisites/Setup: Briefly mention how to start a project (
npm create vue@latest).
- Step 1: Setup Pinia: Editing
main.js.
- Step 2: Create Module 1 (User Store):
- State:
isLoggedIn, user.
- Actions:
login, logout.
- Getters:
fullName.
- Step 3: Create Module 2 (Product/Cart Store):
- State:
items.
- Actions:
addToCart.
- Getters:
cartTotal.
- Crucial step: Show how to access one store from another (Cross-store interaction). E.g.,
useCartStore checking if useUserStore is logged in before adding an item.
- Step 4: Create Components:
- A component to display user info.
- A component to display the cart.
- Step 5: Composables (Optional but recommended): Maybe keep it simple for now, stick to stores + components.
- Directory Structure Visual: Provide a tree view.
-
Drafting the Code (Mental or scratchpad):
- Setup:
const pinia = createPinia(); app.use(pinia);
- User Store:
export const useUserStore = defineStore('user', () => {
const user = ref(null);
const login = () => { ... }
return { user, login }
})
- Cart Store:
export const useCartStore = defineStore('cart', () => {
const items = ref([]);
const userStore = useUserStore(); // Cross-store usage
const addItem = (item) => {
if(!userStore.isLoggedIn) throw new Error("Login required");
items.value.push(item);
}
return { items, addItem }
})
-
Refining the "Design" Aspect:
- It's not just code; it's about the pattern.
- Explain why we are doing this (Separation of Concerns).
- Explain the Setup Stores vs Option Stores. I'll choose Setup Stores (Composition API style) as it's the modern Vue 3 recommendation and aligns better with modular thinking (functions, refs, computed).
-
Finalizing the Output Structure:
- Introduction: Brief overview.
- Project Structure: ASCII tree.
- Installation: Command line.
- Core Implementation:
- Main entry point.
- Store 1 (Auth).
- Store 2 (Products/Cart) + Cross-store communication.
- View Layer: How to use them in
.vue files.
- Best Practices: Tips on modular design (persisting state, typing).
-
Self-Correction during drafting:
- Issue: Should I use
mapState or storeToRefs?
- Decision: In Vue 3 Composition API,
storeToRefs is essential to keep reactivity when destructuring. I must emphasize this.
- Issue: How to handle cross-store logic?
- Decision: Use the "Composable" pattern within the store definition. Call
const otherStore = useOtherStore() inside the action.
-
Writing the response: (This aligns with the provided good response). I will ensure the code is clean, commented, and follows modern standards (Vite + Vue 3 + Pinia).
(Self-Correction): Make sure to define "Modular" clearly. In Pinia, every store is inherently a module. You don't need a specific "modules" object like in Vuex. I need to make sure the user understands that stores/user.js acts as a module automatically.
-
Final Polish: Check for syntax errors. Ensure import paths look realistic. Add a "Why Pinia?" section to conclude.
(Self-Correction - Detailed Code Check):
defineStore('user', () => ...) -> Correct.
const userStore = useUserStore() inside useCartStore -> This is the specific feature requested for "modular" interaction.
Proceed to generate output based on this structure.
This design outlines a scalable Vue 3 application architecture using Pinia for state management.
In Pinia, "modular" design is built-in. Pinia stores are inherently isolated; you don't need to manually register modules like in Vuex. Each file is essentially its own module.
1. Project Structure
A clean folder structure is essential for modular design.
src/
├── stores/
│ ├── index.js # (Optional) Pinia initialization
│ ├── auth.js # Auth store (User state)
│ └── cart.js # Cart store (Product state)
├── components/
│ ├── UserProfile.vue # Consumes Auth Store
│ └── ShoppingCart.vue # Consumes Cart Store
├── App.vue
└── main.js
2. Setup and Initialization
First, ensure you have Pinia installed:
npm install pinia
src/main.js
We initialize Pinia here and pass it to the Vue app instance.
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app')
3. Designing the Stores (The Modules)
We will use the Setup Store syntax (standard functions/computed/refs) as it is the most flexible and idiomatic for Vue 3.
Module A: Auth Store (src/stores/auth.js)
Handles user data and login status.
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useAuthStore = defineStore('auth', () => {
// State
const user = ref(null)
const isLoading = ref(false)
// Getters
const isLoggedIn = computed(() => !!user.value)
const userName = computed(() => user.value?.name || 'Guest')
// Actions
async function login(username, password) {
isLoading.value = true
// Simulate API call
return new Promise((resolve) => {
setTimeout(() => {
user.value = { id: 1, name: username }
isLoading.value = false
resolve(true)
}, 1000)
})
}
function logout() {
user.value = null
}
return { user, isLoading, isLoggedIn, userName, login, logout }
})
Module B: Cart Store (src/stores/cart.js)
Handles shopping cart logic.
Note: This demonstrates Cross-Store Interaction (accessing Auth state from Cart state).
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useAuthStore } from './auth' // Import other store
export const useCartStore = defineStore('cart', () => {
// State
const items = ref([])
// Getters
const cartCount = computed(() => items.value.length)
const cartTotal = computed(() =>
items.value.reduce((acc, item) => acc + item.price, 0)
)
// Actions
function addToCart(product) {
const authStore = useAuthStore() // Instantiating Auth Store
// Cross-Store Logic: Check login before adding to cart
if (!authStore.isLoggedIn) {
alert('Please log in to add items to cart')
return false
}
items.value.push(product)
return true
}
function clearCart() {
items.value = []
}
return { items, cartCount, cartTotal, addToCart, clearCart }
})
4. Component Consumption
Components consume these stores using the composition API.
Component: User Profile (src/components/UserProfile.vue)
<template>
<div class="user-card">
<p v-if="authStore.isLoading">Loading...</p>
<div v-else>
<p>User: {{ authStore.userName }}</p>
<p>Status: {{ authStore.isLoggedIn ? 'Logged In' : 'Guest' }}</p>
<button v-if="!authStore.isLoggedIn" @click="handleLogin">
Login (Simulate)
</button>
<button v-else @click="authStore.logout">
Logout
</button>
</div>
</div>
</template>
<script setup>
import { useAuthStore } from '../stores/auth'
// 1. Initialize the store
const authStore = useAuthStore()
// 2. Use actions
const handleLogin = () => {
authStore.login('JohnDoe', '123')
}
</script>
Component: Shopping Cart (src/components/ShoppingCart.vue)
<template>
<div class="cart">
<h3>Cart ({{ cartStore.cartCount }} items)</h3>
<p>Total: ${{ cartStore.cartTotal }}</p>
<button @click="addSampleItem">Add Item ($50)</button>
<button @click="cartStore.clearCart">Clear</button>
<ul>
<li v-for="(item, index) in cartStore.items" :key="index">
{{ item.name }} - ${{ item.price }}
</li>
</ul>
</div>
</template>
<script setup>
import { useCartStore } from '../stores/cart'
const cartStore = useCartStore()
const addSampleItem = () => {
cartStore.addToCart({ id: Date.now(), name: 'Product A', price: 50 })
}
</script>
5. App Integration (App.vue)
We bring the components together. Note that state is reactive across components automatically. If you log in via UserProfile, ShoppingCart will immediately gain the ability to add items.
<template>
<div style="display: flex; gap: 2rem; padding: 2rem;">
<UserProfile />
<ShoppingCart />
</div>
</template>
<script setup>
import UserProfile from './components/UserProfile.vue'
import ShoppingCart from './components/ShoppingCart.vue'
</script>
6. Advanced Modular Concepts
For larger applications, consider these advanced patterns:
1. Composing Stores
As shown in cart.js, you can call useAuthStore() inside useCartStore(). Pinia handles the dependency injection automatically, preventing circular dependency issues if structured correctly.
2. Plugins (Persistence)
To persist your modules (e.g., save the cart to LocalStorage), you can add a plugin in main.js or specific state properties using the watch function from Vue.
3. Dynamic Stores
If you have hundreds of modules (e.g., one store per widget), you don't need to import them all in main.js. You can import and call useXyzStore() only inside the components that need them. Pinia will register them lazily.