实战

Claude Code 开发 Vue 3 应用完整指南:组合式 API、Pinia 状态管理与 Vite 实战

Claude Code 辅助 Vue 3 开发完整教程:Composition API 组件生成、TypeScript 集成、Pinia 状态管理、Vue Router 路由配置、Vite 构建优化、组件单元测试(Vitest + Vue Test Utils),以及 Vue 3 项目重构和性能优化的 AI 辅助工作流。

2026/3/164分钟 阅读ClaudeEagle

Claude Code 对 Vue 3 生态有很好的支持,熟悉 Composition API、Pinia、Vue Router 等现代 Vue 栈。 本文展示完整的 Vue 3 开发工作流。

项目初始化

bash
npm create vue@latest my-vue-app
# 选择:TypeScript ✅, Vue Router ✅, Pinia ✅, Vitest ✅, ESLint ✅
cd my-vue-app && npm install
claude  # 开始 AI 辅助开发

CLAUDE.md 配置(Vue 3 项目)

markdown
## Vue 3 技术栈
- Vue 3 + TypeScript
- 状态管理:Pinia
- 路由:Vue Router 4
- 样式:Tailwind CSS / UnoCSS
- 测试:Vitest + Vue Test Utils
- 构建:Vite

## 代码规范
- 使用 Composition API(<script setup> 语法)
- Props 和 Emits 必须有 TypeScript 类型定义
- 复杂逻辑抽成 composables(src/composables/)
- 组件文件:PascalCase.vue
- 不使用 Options API(除非迁移旧代码)

## 命令
- 开发:npm run dev
- 测试:npm run test
- 构建:npm run build

工作流 1:生成 Vue 组件

Create a Vue 3 component: ProductCard Props: - product: { id, name, price, image, rating, stock } - showAddToCart?: boolean (default: true) Emits: - add-to-cart(product) - view-detail(productId) Features: - Show product image with fallback - Star rating display (1-5) - Out of stock badge when stock === 0 - Add to cart button (disabled when out of stock) - Hover effect with shadow Tech: <script setup> + TypeScript + Tailwind CSS File: src/components/ProductCard.vue

生成示例:

vue
<script setup lang="ts">
interface Product {
  id: string
  name: string
  price: number
  image: string
  rating: number
  stock: number
}

interface Props {
  product: Product
  showAddToCart?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  showAddToCart: true
})

const emit = defineEmits<{
  'add-to-cart': [product: Product]
  'view-detail': [productId: string]
}>()

const isOutOfStock = computed(() => props.product.stock === 0)
</script>

<template>
  <div class="rounded-lg shadow hover:shadow-md transition-shadow cursor-pointer"
       @click="emit('view-detail', product.id)">
    <!-- 组件内容 -->
  </div>
</template>

工作流 2:Pinia Store 生成

Create a Pinia store for cart management: useCartStore State: - items: CartItem[] (product + quantity) - loading: boolean Getters: - totalItems: number (sum of quantities) - totalPrice: number - isEmpty: boolean Actions: - addItem(product, quantity = 1) - removeItem(productId) - updateQuantity(productId, quantity) - clearCart() - checkout(): Promise (mock API call) File: src/stores/cart.ts Use defineStore with Composition API style

工作流 3:Vue Router 路由配置

Set up Vue Router for an e-commerce app: Routes: / → HomeView (lazy loaded) /products → ProductListView /products/:id → ProductDetailView /cart → CartView (requires auth) /checkout → CheckoutView (requires auth) /account → AccountView (requires auth, has children: profile, orders, settings) /login → LoginView (redirect if already logged in) 404 → NotFoundView Add: - Navigation guards for auth routes - Scroll behavior (scroll to top on navigation) - Route meta (title, requiresAuth) - Lazy loading for all views File: src/router/index.ts

工作流 4:Composable 提取

Extract reusable logic from this component into composables: [粘贴组件代码] Identify logic that should be: 1. useFetch(url) - generic data fetching with loading/error state 2. useInfiniteScroll(loadMore) - intersection observer scroll loading 3. useLocalStorage(key, defaultValue) - reactive localStorage sync Create each composable in src/composables/ Make them TypeScript generic where appropriate

工作流 5:组件测试

Write Vitest + Vue Test Utils tests for ProductCard component. Test cases: 1. Renders product name, price, image 2. Shows "Out of Stock" badge when stock === 0 3. Add to cart button disabled when out of stock 4. Emits 'add-to-cart' event when button clicked 5. Emits 'view-detail' event when card clicked 6. Star rating displays correctly for rating=3.5 7. Image fallback shows when src fails Use: - @vue/test-utils mount - vi.fn() for event handler mocks - @testing-library/vue for accessible queries File: src/components/__tests__/ProductCard.test.ts

工作流 6:Options API 迁移到 Composition API

Migrate this Vue 2 Options API component to Vue 3 Composition API: [粘贴旧组件] Requirements: 1. Use <script setup> syntax 2. Replace data() with ref/reactive 3. Replace computed with computed() 4. Replace methods with plain functions 5. Replace lifecycle hooks with onMounted/onUnmounted etc. 6. Replace Vuex mapState/mapActions with Pinia store 7. Add TypeScript types 8. Keep the same template (only update binding syntax if needed)

工作流 7:Vite 构建优化

Analyze and optimize the Vite build config for production. Our current build output: 2.8MB main chunk. Please: 1. Configure manual chunk splitting (vendor / router / ui) 2. Add dynamic imports for heavy libraries (charts, editors) 3. Configure asset optimization (image compression) 4. Add bundle analyzer (rollup-plugin-visualizer) 5. Configure proper cache headers strategy File: vite.config.ts

来源:Anthropic 官方文档 + Vue 3 官方文档

相关文章推荐

实战Claude Code Vue 3 实战完全指南:Composition API 开发到企业级前端工程化Claude Code 辅助 Vue 3 开发的完整实战指南:Composition API 组件生成(setup/ref/computed)、Pinia 状态管理代码生成、Vue Router 4 路由配置、TypeScript 类型定义生成(Props/Emits)、Composables 抽象、Vitest 单元测试生成、性能优化(虚拟滚动/v-memo),以及 Options API 迁移和响应式丢失问题排查的 Prompt 模板。2026/3/26实战Claude Code Skills 实战:15 个可直接使用的 SKILL.md 模板(Git/审查/测试/文档/部署/调试)15 个精心设计的开箱即用 SKILL.md 模板:Git 工作流类(Smart Commit/PR Creator/Branch Cleanup);代码审查类(Security Review 含 OWASP 清单/Performance Review N+1 检测);测试类(Test Generator/Coverage Check);文档类(API Doc Generator OpenAPI 格式/Changelog Generator);部署运维类(Pre-deploy Checklist);调试类(Error Analyzer);效率工具类(Code Explainer/Refactor Advisor/Dependency Auditor/Daily Standup Helper)。2026/5/10实战Claude Code 成本优化完整指南:Token 节省策略、模型选择和 Prompt Cache 配置Claude Code 成本优化完整指南:Token 消耗来源分析(对话历史/大文件读取/工具输出/MCP 服务器/长 CLAUDE.md);8 个优化策略(/compact 主动压缩/精确 @ 引用/控制 MCP 数量/模型选择 Haiku vs Sonnet vs Opus 价格对比/努力等级按需调整/Prompt Cache 1 小时 TTL/CLAUDE.md 精简/usage 监控);不同场景的成本估算(个人/小团队/企业);以及订阅 vs API 的临界点分析。2026/5/8实战Claude Code 企业规模化最佳实践:AI 网关、成本控制和可观测性完全指南Claude Code 企业级部署完整指南:原生局限(订阅模式无实时仪表盘/API 密钥散落风险);AI 网关层解决方案(7 个最佳实践:凭证三级层级/预算速率限制/完整请求可观测性/请求元数据标签/多提供商故障转移/输入输出护栏/灵活提供商切换);Portkey 2 分钟配置示例;Enterprise 专属功能(managed-settings/allowManagedDomainsOnly/OpenTelemetry);以及团队 CLAUDE.md 安全策略模板。2026/5/7实战Claude Code 45 个进阶技巧:8.1k Star 的 GitHub 精华整理ykdojo GitHub 仓库(8100+ Stars)45 个 Claude Code 实战技巧精华整理:自定义状态栏显示 Token 消耗;Git CLI 配合自动创建 PR;Gemini CLI 作为助手处理被限制的搜索;/compact 带焦点提示词保留关键信息;Fork 会话和半克隆技术;容器安全运行高风险任务;CLAUDE.md vs Skills vs Slash Commands vs Plugins 的区别;/loop 定期轮询;以及 dx 插件安装。2026/5/6实战Claude Code 全软件开发生命周期实战:从需求到运维的端到端工作流指南Claude Code 覆盖完整 SDLC 的端到端工作流:需求拆解和 ADR 生成、TDD 验证循环配置(质量 2-3×)、分层实现+Git Worktree 并行、多角度并行 PR 审查、GitHub Actions CI/CD 配置、OpenAPI 文档自动生成、生产日志分析和性能分析,各阶段效率提升数据对比。2026/4/24