Przejdź do głównej zawartości

Vue.js Development Patterns

Ta treść nie jest jeszcze dostępna w Twoim języku.

Harness the power of Cursor IDE and Claude Code for Vue.js development. These patterns cover Vue 3 Composition API, Vuex/Pinia state management, component design, and testing strategies optimized for AI assistance.

  1. Open Cursor in your projects directory
  2. Configure Figma MCP if needed: Settings > MCP > Add Server > http://127.0.0.1:3845/sse
  3. Activate Agent mode (Cmd/Ctrl + I)
  4. Prompt: “Create a new Vue 3 project with TypeScript, Vite, Pinia for state management, Vue Router, and Vitest for testing”
  5. Enable YOLO mode to automatically run all setup commands
  6. Review the generated configuration and project structure
.mcp.json
{
"mcpServers": {
"figma": {
"type": "sse",
"url": "http://127.0.0.1:3845/sse"
}
}
}

Create rules to guide AI in Vue development:

.cursor/rules/vue-patterns.md
# Vue.js Development Standards
## Component Guidelines
- Use Vue 3 Composition API with <script setup>
- TypeScript for all components
- Single File Components (SFC) with logical ordering: template, script, style
- Props validation with TypeScript interfaces
## State Management
- Pinia for global state management
- Composables for shared logic
- Reactive/ref for local state
- Avoid Options API unless maintaining legacy code
## Testing Strategy
- Component tests with @vue/test-utils
- E2E tests with Playwright
- Unit test composables and stores

Scenario: Convert a design mockup to a Vue component

Using Figma MCP Server:

Terminal window
# PRD: Convert Figma designs to Vue components
# Plan: Use Figma MCP for accurate design-to-code
# Enable Figma MCP in Figma Desktop
# Preferences > Enable Dev Mode MCP Server
# Todo:
# - [ ] Select component in Figma
# - [ ] Generate Vue component with design tokens
# - [ ] Extract variables for theming
# - [ ] Create responsive variants

Cursor Workflow with Figma MCP:

1. Select the component in Figma (MCP server running)
2. Prompt: "Using Figma MCP, generate a Vue 3 SFC from the selected design. Use <script setup>, TypeScript, and Tailwind CSS"
3. Extract tokens: "Get all design variables from Figma and create a Vue theme configuration"
4. Follow up: "Add proper prop types and emit events for user interactions"

Manual Approach (without MCP):

1. Screenshot or export the design
2. Drag image into Cursor chat
3. Prompt: "Create a Vue 3 component using Composition API and TypeScript based on this design. Use Tailwind CSS and make it responsive"

Custom Composables:

Cursor/Claude Prompt
Create a useInfiniteScroll composable that:
1. Accepts a callback function for loading more data
2. Tracks loading and error states
3. Handles intersection observer for trigger element
4. Provides pagination info (current page, hasMore)
5. Includes TypeScript types
6. Add comprehensive JSDoc comments
7. Include usage example

Cursor Agent Mode Example:

Create a Pinia store for managing a shopping cart with:
- TypeScript interfaces for Product and CartItem
- Actions: addItem, removeItem, updateQuantity, clearCart
- Getters: totalPrice, itemCount, formattedCart
- Persist to localStorage
- Optimistic updates with rollback on error
- Integration with Vue Router for cart page
  1. Module Organization

    Generate a modular Pinia store structure for our e-commerce app:
    - User store (auth, profile, preferences)
    - Product store (catalog, filters, search)
    - Cart store (items, calculations)
    - Order store (history, tracking)
    With proper TypeScript types and cross-store communication
  2. Store Composition

    Show how to compose multiple stores together for the checkout flow,
    accessing user data, cart items, and creating orders
  3. Testing Stores

    Write unit tests for the cart store including:
    - Adding/removing items
    - Price calculations
    - Persistence functionality
    - Error handling

Claude Code Recipe:

Set up Vue Router with:
1. Nested routes for /products, /products/:id, /products/:id/reviews
2. Route guards for authentication
3. Lazy loading for all route components
4. Breadcrumb generation from routes
5. TypeScript types for route params
6. 404 handling with custom component
Implement authentication flow in Vue Router:
- beforeEach guard checking auth status
- Redirect to login if not authenticated
- Store intended route for post-login redirect
- Progress indicator during route changes
- Handle async permission checks
- TypeScript types for meta fields
Terminal window
# Use Figma MCP to create Vue theme
"Using Figma MCP get_variable_defs:
1. Extract all color variables from the design system
2. Get typography and spacing tokens
3. Generate a Vue composable for theme management"
composables/useTheme.ts
// Generated theme composable
import { computed } from 'vue'
export const useTheme = () => {
const colors = {
primary: {
base: '#1D4ED8', // Figma: Primary/Blue
hover: '#1E40AF', // Figma: Primary/Blue-Dark
light: '#3B82F6' // Figma: Primary/Blue-Light
},
text: {
primary: '#1F2937', // Figma: Text/Primary
secondary: '#6B7280' // Figma: Text/Secondary
}
}
const spacing = {
xs: '0.5rem', // Figma: Spacing/XS (8px)
sm: '1rem', // Figma: Spacing/S (16px)
md: '1.5rem', // Figma: Spacing/M (24px)
lg: '2rem' // Figma: Spacing/L (32px)
}
return {
colors: computed(() => colors),
spacing: computed(() => spacing)
}
}
Terminal window
# Generate Vue component library from Figma design system
"Using Figma MCP with Code Connect:
1. Scan all components in the design system
2. Generate Vue components matching each Figma component
3. Use our existing base components where mapped
4. Create Storybook stories for each component"
# Example workflow
"Select the Button component in Figma and:
- Generate Vue component with all variants
- Extract props from Figma component properties
- Apply design tokens for consistent theming
- Create TypeScript interfaces for props"
Analyze UserList.vue component and optimize:
1. Implement virtual scrolling for large lists
2. Add proper key bindings
3. Use shallowRef where appropriate
4. Implement memo for expensive computations
5. Add lazy loading for images
6. Optimize re-renders with v-memo

Component Testing Pattern:

Test Generation Prompt
Generate comprehensive tests for ProductCard.vue:
1. Mount component with different props
2. Test user interactions (click, hover)
3. Verify emitted events
4. Test conditional rendering
5. Check accessibility attributes
6. Mock Pinia store interactions
7. Test error states
8. Snapshot testing for UI consistency

E2E Testing Workflow:

Create Playwright tests for our checkout flow:
- Navigate to product page
- Add items to cart
- Proceed to checkout
- Fill payment form
- Verify order confirmation
- Test error scenarios
- Mobile responsive testing
Create a DataTable component with full TypeScript support:
- Generic type for row data
- Typed column definitions
- Type-safe sorting and filtering
- Properly typed slots
- Event emitters with payload types
- Discriminated unions for cell renderers
Build a type-safe API composable:
1. Generic function for different endpoints
2. Proper error type handling
3. Loading and data state types
4. Abort controller integration
5. Request/response interceptors
6. Type inference from endpoint

Diagnosis Pattern:

My Vue component isn't updating when data changes.
Help me debug by:
1. Checking reactivity breaks
2. Identifying mutation vs reassignment
3. Verifying computed dependencies
4. Checking for stale closures
5. Adding debug logs for reactive values
Review components/ directory for potential memory leaks:
- Event listener cleanup in onUnmounted
- Interval/timeout clearing
- Intersection observer disconnection
- WebSocket connection closure
- Store subscription cleanup
Set up a Nuxt 3 project with:
1. File-based routing
2. API routes in /server/api
3. Pinia integration
4. Custom error page
5. SEO optimization with useHead
6. Environment variable handling
7. Nitro server configuration
Implement SSR-safe patterns for:
- Browser-only API usage
- Hydration-safe random values
- Cookie-based authentication
- API data fetching strategies
- Client-only component wrapping
Create a component library setup:
1. Base components with Tailwind
2. Dark mode support
3. Configurable theme
4. Compound components pattern
5. Accessible by default
6. Storybook integration