Manage application state efficiently with Pinia, Vue's official state management solution.
# Pinia State Management for Vue in Google Antigravity
Master Pinia state management in your Google Antigravity Vue.js projects. This guide covers store creation, composition API patterns, persistence, and advanced state management techniques.
## Store Definition Patterns
Create type-safe Pinia stores:
```typescript
// src/stores/user.ts
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type { User, UpdateProfilePayload } from "@/types/user";
import { api } from "@/lib/api";
// Composition API style (recommended)
export const useUserStore = defineStore("user", () => {
// State
const user = ref<User | null>(null);
const isLoading = ref(false);
const error = ref<string | null>(null);
// Getters
const isAuthenticated = computed(() => !!user.value);
const fullName = computed(() => {
if (!user.value) return "";
return `${user.value.firstName} ${user.value.lastName}`.trim();
});
const isAdmin = computed(() => user.value?.role === "admin");
// Actions
async function fetchUser() {
isLoading.value = true;
error.value = null;
try {
const response = await api.get<User>("/users/me");
user.value = response.data;
} catch (err) {
error.value = err instanceof Error ? err.message : "Failed to fetch user";
user.value = null;
} finally {
isLoading.value = false;
}
}
async function updateProfile(payload: UpdateProfilePayload) {
if (!user.value) return;
isLoading.value = true;
error.value = null;
try {
const response = await api.patch<User>(`/users/${user.value.id}`, payload);
user.value = response.data;
} catch (err) {
error.value = err instanceof Error ? err.message : "Failed to update profile";
throw err;
} finally {
isLoading.value = false;
}
}
async function logout() {
try {
await api.post("/auth/logout");
} finally {
user.value = null;
// Clear other stores if needed
const cartStore = useCartStore();
cartStore.$reset();
}
}
function setUser(newUser: User) {
user.value = newUser;
}
function $reset() {
user.value = null;
isLoading.value = false;
error.value = null;
}
return {
// State
user,
isLoading,
error,
// Getters
isAuthenticated,
fullName,
isAdmin,
// Actions
fetchUser,
updateProfile,
logout,
setUser,
$reset,
};
});
```
## Cart Store with Persistence
Implement a persistent shopping cart:
```typescript
// src/stores/cart.ts
import { defineStore } from "pinia";
import { ref, computed, watch } from "vue";
interface CartItem {
id: string;
productId: string;
name: string;
price: number;
quantity: number;
image: string;
}
export const useCartStore = defineStore("cart", () => {
// State with localStorage initialization
const items = ref<CartItem[]>([]);
const isOpen = ref(false);
// Initialize from localStorage
function initFromStorage() {
const stored = localStorage.getItem("cart");
if (stored) {
try {
items.value = JSON.parse(stored);
} catch {
items.value = [];
}
}
}
// Persist to localStorage on changes
watch(
items,
(newItems) => {
localStorage.setItem("cart", JSON.stringify(newItems));
},
{ deep: true }
);
// Getters
const itemCount = computed(() => {
return items.value.reduce((sum, item) => sum + item.quantity, 0);
});
const subtotal = computed(() => {
return items.value.reduce(
(sum, item) => sum + item.price * item.quantity,
0
);
});
const tax = computed(() => subtotal.value * 0.1);
const total = computed(() => subtotal.value + tax.value);
const isEmpty = computed(() => items.value.length === 0);
// Actions
function addItem(product: Omit<CartItem, "id" | "quantity">) {
const existingItem = items.value.find(
(item) => item.productId === product.productId
);
if (existingItem) {
existingItem.quantity++;
} else {
items.value.push({
...product,
id: crypto.randomUUID(),
quantity: 1,
});
}
isOpen.value = true;
}
function removeItem(id: string) {
const index = items.value.findIndex((item) => item.id === id);
if (index > -1) {
items.value.splice(index, 1);
}
}
function updateQuantity(id: string, quantity: number) {
const item = items.value.find((item) => item.id === id);
if (item) {
if (quantity <= 0) {
removeItem(id);
} else {
item.quantity = quantity;
}
}
}
function clearCart() {
items.value = [];
}
function toggleCart() {
isOpen.value = !isOpen.value;
}
function $reset() {
items.value = [];
isOpen.value = false;
localStorage.removeItem("cart");
}
// Initialize on store creation
initFromStorage();
return {
items,
isOpen,
itemCount,
subtotal,
tax,
total,
isEmpty,
addItem,
removeItem,
updateQuantity,
clearCart,
toggleCart,
$reset,
};
});
```
## Store Composition
Compose stores together:
```typescript
// src/stores/checkout.ts
import { defineStore, storeToRefs } from "pinia";
import { ref, computed } from "vue";
import { useCartStore } from "./cart";
import { useUserStore } from "./user";
import type { Address, PaymentMethod } from "@/types/checkout";
export const useCheckoutStore = defineStore("checkout", () => {
const cartStore = useCartStore();
const userStore = useUserStore();
// State
const step = ref<1 | 2 | 3 | 4>(1);
const shippingAddress = ref<Address | null>(null);
const billingAddress = ref<Address | null>(null);
const useSameAddress = ref(true);
const paymentMethod = ref<PaymentMethod | null>(null);
const isProcessing = ref(false);
const error = ref<string | null>(null);
// Getters from other stores
const { items, total: cartTotal } = storeToRefs(cartStore);
const { user } = storeToRefs(userStore);
// Computed
const shippingCost = computed(() => {
if (cartTotal.value >= 100) return 0;
return 9.99;
});
const orderTotal = computed(() => {
return cartTotal.value + shippingCost.value;
});
const canProceed = computed(() => {
switch (step.value) {
case 1:
return !!shippingAddress.value;
case 2:
return useSameAddress.value || !!billingAddress.value;
case 3:
return !!paymentMethod.value;
default:
return false;
}
});
// Actions
function nextStep() {
if (step.value < 4 && canProceed.value) {
step.value = (step.value + 1) as 1 | 2 | 3 | 4;
}
}
function previousStep() {
if (step.value > 1) {
step.value = (step.value - 1) as 1 | 2 | 3 | 4;
}
}
function setShippingAddress(address: Address) {
shippingAddress.value = address;
if (useSameAddress.value) {
billingAddress.value = address;
}
}
async function submitOrder() {
if (!canProceed.value || !paymentMethod.value) return;
isProcessing.value = true;
error.value = null;
try {
const orderData = {
items: items.value,
shippingAddress: shippingAddress.value,
billingAddress: useSameAddress.value
? shippingAddress.value
: billingAddress.value,
paymentMethod: paymentMethod.value,
total: orderTotal.value,
};
const response = await api.post("/orders", orderData);
// Clear cart on success
cartStore.clearCart();
return response.data;
} catch (err) {
error.value = err instanceof Error ? err.message : "Order failed";
throw err;
} finally {
isProcessing.value = false;
}
}
function $reset() {
step.value = 1;
shippingAddress.value = null;
billingAddress.value = null;
useSameAddress.value = true;
paymentMethod.value = null;
isProcessing.value = false;
error.value = null;
}
return {
step,
shippingAddress,
billingAddress,
useSameAddress,
paymentMethod,
isProcessing,
error,
shippingCost,
orderTotal,
canProceed,
items,
cartTotal,
nextStep,
previousStep,
setShippingAddress,
submitOrder,
$reset,
};
});
```
## Component Integration
Use stores in Vue components:
```vue
<!-- src/components/Cart/CartDrawer.vue -->
<template>
<Transition name="slide">
<div
v-if="isOpen"
class="fixed inset-0 z-50 overflow-hidden"
@click.self="toggleCart"
>
<div class="absolute inset-y-0 right-0 w-full max-w-md bg-gray-900 shadow-xl">
<div class="flex h-full flex-col">
<!-- Header -->
<div class="flex items-center justify-between border-b border-gray-800 px-4 py-4">
<h2 class="text-lg font-semibold text-white">
Cart ({{ itemCount }})
</h2>
<button @click="toggleCart" class="text-gray-400 hover:text-white">
<XIcon class="h-6 w-6" />
</button>
</div>
<!-- Items -->
<div class="flex-1 overflow-y-auto px-4 py-4">
<div v-if="isEmpty" class="text-center text-gray-400 py-12">
Your cart is empty
</div>
<div v-else class="space-y-4">
<CartItem
v-for="item in items"
:key="item.id"
:item="item"
@remove="removeItem"
@update-quantity="updateQuantity"
/>
</div>
</div>
<!-- Footer -->
<div v-if="!isEmpty" class="border-t border-gray-800 px-4 py-4">
<div class="flex justify-between text-lg font-semibold text-white mb-4">
<span>Total</span>
<span>${{ total.toFixed(2) }}</span>
</div>
<button
@click="goToCheckout"
class="w-full rounded-lg bg-indigo-500 py-3 font-medium text-white hover:bg-indigo-600"
>
Checkout
</button>
</div>
</div>
</div>
</div>
</Transition>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useCartStore } from "@/stores/cart";
import { useRouter } from "vue-router";
const router = useRouter();
const cartStore = useCartStore();
const {
items,
isOpen,
itemCount,
total,
isEmpty,
} = storeToRefs(cartStore);
const {
toggleCart,
removeItem,
updateQuantity,
} = cartStore;
function goToCheckout() {
toggleCart();
router.push("/checkout");
}
</script>
```
Google Antigravity generates comprehensive Pinia state management with type-safe stores, persistence patterns, and composable store architecture for Vue.js applications.This Vue.js prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their vue.js implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Vue.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.