实战

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 跨会话协作实战:用 SendMessage 和 ListAgents 串联你的多台设备解析 Claude Code v2.1.224 新增的跨会话消息能力,探讨 SendMessage/ListAgents 的实战用法、crossSessionInbound 安全边界与多设备协作的应用潜力。2026/8/7实战Claude Code 长会话优化实战:让 CLAUDE.md 规则在 Compaction 后依然存活实战教学:基于官方 Compaction 存活规则表,指导你如何重新组织 CLAUDE.md 规则、调整 SKILL.md 写作顺序、合理使用 /compact focus 和 /clear,确保关键约定在长会话压缩后仍然存活,附完整检查清单。2026/7/12实战Claude Code Agent Teams 实战:三视角协作设计一个 CLI 工具基于官方文档实例,实战演示如何启用 Claude Code Agent Teams 并用三个视角(UX、技术架构、唱反调)协作探索一个 CLI 工具的设计方案,详解空闲行显示逻辑、折叠交互、In-process 与 Split panes 两种显示模式的适用场景。2026/7/12实战Claude Code 实战:Desktop 内置浏览器 + Auto Mode 组合,从查文档到自动提交 PR通过一个真实集成第三方 API 的完整场景,演示 Claude Code Desktop 内置浏览器与 Auto Mode 组合使用如何实现从查阅官方文档、编写集成代码、本地预览验证到提交推送创建 PR 的端到端自动化,并梳理背后的多层安全边界设计。2026/7/11实战Claude Code 生产力工具箱:MCP + GitHub Actions + Prompt Caching 三件套实战组合实战讲解如何组合 MCP 数据连接、GitHub Actions 自动化和 Prompt Caching 优化,搭建从 Issue 到 PR 的完整自动化工作流,并给出权限最小化配置和团队级实战检查清单。2026/7/6