Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

\n```\n\nGoogle Antigravity generates comprehensive Pinia state management with type-safe stores, persistence patterns, and composable store architecture for Vue.js applications.","author":{"@type":"Person","name":"Community"},"dateCreated":"2025-11-22T01:16:29.929656+00:00","keywords":"Vue.js, Pinia, State Management, Vuex","programmingLanguage":"Antigravity AI Prompt","codeRepository":"https://antigravityai.directory"}
Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Pinia State Management for Vue

Pinia State Management for Vue

Manage application state efficiently with Pinia, Vue's official state management solution.

Vue.jsPiniaState ManagementVuex
by Community
⭐0Stars
👁️4Views
.antigravity
# 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.

When to Use This Prompt

This Vue.js prompt is ideal for developers working on:

  • Vue.js applications requiring modern best practices and optimal performance
  • Projects that need production-ready Vue.js code with proper error handling
  • Teams looking to standardize their vue.js development workflow
  • Developers wanting to learn industry-standard Vue.js patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the Vue.js code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this Vue.js prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...