Analyzing Application Structure
I'm currently focused on the user's need for a modular Vue 3 application built with Pinia. I'm prioritizing the design and structure, which, as I see it, means going beyond basic examples and diving into how to organize state management in a scalable way. My aim is a solid, practical blueprint, not just a proof-of-concept.
Mapping Out Components
I've sketched out the initial component structure. Given the User and Cart domains, the application will need components to represent them. I'm visualizing the components with clear responsibility separation: UserLogin, UserProfile, ProductList, CartDisplay, and CartItem. I'm focusing on their interaction with the Pinia stores for data flow, and how the state will be shared.
Outlining the Application's Anatomy
My thoughts now lean towards concrete implementation. I'm focusing on defining the products.js store, planning a simple array of products to simulate fetching data. Then, the trickier part, the cart.js store: It'll need to reference product prices from the products store to calculate the total cost, which is where things get interesting, showcasing how Pinia's stores can interact and share state across domains. I'm visualizing the actions and getters.
Planning Modularization Strategy
Now, I'm delving deeper into the best approach for application modularity. I've decided to concentrate on structuring the stores by domain: user, products, and cart. Each will handle its data and logic independently, which will be the first step in ensuring good separation of concerns. The trickiest part will be the cart store's dependency on the products store for total calculations.
Refining the Approach
I'm now iterating on the design. I've decided to prioritize clarity over complexity, so I'm simplifying the User authentication flow. Instead, I'm focusing my efforts on a more in-depth exploration of the Cart store's dependency on the Products store. The core idea remains the same, but the implementation will be more practical, so it is easier to understand how to share state between modules.
Evaluating E-Commerce Example
I've decided to refine the example to focus even more on the key features. Rather than a rudimentary product list, I am going with the User and Cart domains, with hardcoded products, to make the interactions more explicit. This will involve the core concepts of Pinia in a simplified but effective way, which focuses the user on the important parts, not the scaffolding. I'll make sure to provide clear instructions, so the focus will not be lost.
Here is a comprehensive design for a Vue 3 application utilizing Pinia for modular state management.
To demonstrate true modularity, we will design a mini E-Commerce flow consisting of three distinct domains (modules):
- Auth: Managing user identity.
- Products: Managing available inventory.
- Cart: Managing selected items and interacting with the Product store for calculation.
1. Project Structure
Organize your stores in a dedicated folder. A common pattern is to name the files based on the logical resource they manage.
src/
├── components/
│ ├── NavBar.vue
│ ├── ProductList.vue
│ └── ShoppingCart.vue
├── stores/ <-- Modular State Directory
│ ├── auth.js (User logic)
│ ├── products.js (Inventory logic)
│ └── cart.js (Checkout logic, interacts with products)
├── App.vue
└── main.js
2. The Stores (Modular Logic)
In Pinia, each file exports a specific hook (conventionally use...Store).
Module A: The Product Store
src/stores/products.js
Responsible for fetching and holding raw product data.
import { defineStore } from 'pinia';
export const useProductStore = defineStore('products', {
state: () => ({
items: [],
loading: false,
}),
getters: {
// Example of a getter: Filter out of stock items
availableItems: (state) => state.items.filter(item => item.inventory > 0)
},
actions: {
async fetchProducts() {
this.loading = true;
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 500));
this.items = [
{ id: 1, name: 'Mechanical Keyboard', price: 150, inventory: 10 },
{ id: 2, name: 'Gaming Mouse', price: 80, inventory: 5 },
{ id: 3, name: 'USB-C Hub', price: 40, inventory: 0 }, // Out of stock
];
this.loading = false;
},
decrementInventory(productId) {
const product = this.items.find(item => item.id === productId);
if (product && product.inventory > 0) {
product.inventory--;
}
}
}
});
Module B: The Auth Store
src/stores/auth.js
Responsible for user session state.
import { defineStore } from 'pinia';
export const useAuthStore = defineStore('auth', {
state: () => ({
user: null, // null means logged out
}),
getters: {
isAuthenticated: (state) => !!state.user,
userName: (state) => state.user ? state.user.name : 'Guest',
},
actions: {
login(username) {
this.user = { name: username, id: Date.now() };
},
logout() {
this.user = null;
}
}
});
Module C: The Cart Store (Cross-Store Composition)
src/stores/cart.js
This is where modularity shines. The Cart store needs to know prices from the Product store to calculate totals.
import { defineStore } from 'pinia';
import { useProductStore } from './products'; // Import other store
export const useCartStore = defineStore('cart', {
state: () => ({
rawItems: [], // Array of { id, quantity }
}),
getters: {
// Calculate total items
itemsCount: (state) => state.rawItems.reduce((acc, item) => acc + item.quantity, 0),
// ADVANCED: Calculate total price using data from Product Store
cartTotal: (state) => {
const productStore = useProductStore(); // Initialize external store
return state.rawItems.reduce((total, cartItem) => {
const product = productStore.items.find(p => p.id === cartItem.id);
return total + (product ? product.price * cartItem.quantity : 0);
}, 0);
}
},
actions: {
addToCart(productId) {
const productStore = useProductStore(); // Initialize external store
// Check inventory in Product Store
const product = productStore.items.find(p => p.id === productId);
if (!product || product.inventory <= 0) return;
// Logic to add to cart
const existingItem = this.rawItems.find(i => i.id === productId);
if (existingItem) {
existingItem.quantity++;
} else {
this.rawItems.push({ id: productId, quantity: 1 });
}
// Update Product Store inventory
productStore.decrementInventory(productId);
},
checkout() {
this.rawItems = [];
alert('Purchase complete!');
}
}
});
3. Application Integration
Main Entry
src/main.js
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
// Initialize Pinia
app.use(createPinia());
app.mount('#app');
4. Component Implementation
Here is how we consume these modular stores inside Vue components using <script setup>.
Component: NavBar (Auth Module)
src/components/NavBar.vue
<template>
<nav>
<h3>Vue Shop</h3>
<div v-if="authStore.isAuthenticated">
Welcome, {{ authStore.userName }} |
Cart: {{ cartStore.itemsCount }} items (${{ cartStore.cartTotal }})
<button @click="authStore.logout">Logout</button>
</div>
<div v-else>
<button @click="authStore.login('Alice')">Login as Alice</button>
</div>
</nav>
</template>
<script setup>
import { useAuthStore } from '@/stores/auth';
import { useCartStore } from '@/stores/cart';
// Instantiate stores
const authStore = useAuthStore();
const cartStore = useCartStore();
</script>
Component: Product List (Products + Cart Module)
src/components/ProductList.vue
Note on Reactivity: We use storeToRefs when destructing state/getters, but we call actions directly from the store instance.
<template>
<div class="product-list">
<h2>Products</h2>
<p v-if="loading">Loading items...</p>
<ul>
<li v-for="product in availableItems" :key="product.id">
{{ product.name }} - ${{ product.price }}
(Remaining: {{ product.inventory }})
<button
@click="cartStore.addToCart(product.id)"
:disabled="!authStore.isAuthenticated"
>
Add to Cart
</button>
</li>
</ul>
<p v-if="!authStore.isAuthenticated" style="color: red;">
Please login to shop.
</p>
</div>
</template>
<script setup>
import { onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { useProductStore } from '@/stores/products';
import { useCartStore } from '@/stores/cart';
import { useAuthStore } from '@/stores/auth';
const productStore = useProductStore();
const cartStore = useCartStore();
const authStore = useAuthStore();
// destructure state/getters safely while keeping reactivity
const { availableItems, loading } = storeToRefs(productStore);
onMounted(() => {
productStore.fetchProducts();
});
</script>
Key Design Principles Used
- Granularity: Stores are separated by domain (
auth, products, cart) rather than one giant global object. This makes code splitting easier and improves maintainability.
- Composition: The
Cart store imports the Products store directly. Pinia detects this dependency and initializes the Product store automatically if usage occurs.
- Direct State Access: Unlike Vuex, no verbose "mutations" are required. We modify state directly in
actions.
- Reactivity Safety: In the components,
storeToRefs is used. If you simply did const { loading } = useProductStore(), reactivity would break. storeToRefs wraps the properties in Vue refs.