实战

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 Plugins 开发指南:封装 Skills、Agents、Hooks 和 MCP ServersClaude Code Plugins 适合把团队工作流从 .claude 本地配置升级为可共享扩展。插件通过 .claude-plugin/plugin.json 描述元数据,skills 使用命名空间避免冲突,可用 --plugin-dir 本地测试。2026/6/8实战Claude Code GitLab CI/CD 完整指南:@claude 创建 MR、Bedrock/Vertex 企业部署Claude Code GitLab CI/CD 官方文档中文整理:beta 状态、工作原理、最小 .gitlab-ci.yml、masked CI/CD variables、issue/MR 评论触发、AI_FLOW_INPUT/AI_FLOW_CONTEXT、GitLab MCP server、Bedrock/Vertex AI 企业认证和安全建议。2026/5/20实战Claude Code GitHub Actions v1 完整指南:@claude 自动开发、PR 审查和 CI 集成Claude Code GitHub Actions 官方文档中文整理:它能做什么、快速安装 /install-github-app、手动配置 GitHub App 和 ANTHROPIC_API_KEY、v1 相比 beta 的破坏性变更、@claude 评论触发、自动 PR 审查、Skills 调用、Daily Report 自动化、权限安全、成本控制和可直接复制的 workflow 模板。2026/5/15实战Claude Code 并行 Worktree 实战:同时跑 4 个 AI 任务的工作流设计Claude Code Worktree 4 种并行工作流模式:功能开发+Bug修复同时进行(3个终端并行、时间节省分析);并行代码审查(PR Worktree审查+继续开发);大规模重构+主线开发(破坏性变更的隔离策略);Subagent 隔离自动并行(4个维度同时分析节省 75% 时间)。不应该并行的场景(有依赖/需共享上下文/单一简单任务)。5 个实用技巧(命名规范、.worktreeinclude、状态监控脚本、PR Worktree 直接推送)。2026/5/13实战Claude Code Routines 实战:6 个可直接使用的 Routine 配置模板6 个开箱即用的 Claude Code Routines 模板:PR 代码审查(GitHub 触发,含 OWASP 安全清单和内联评论格式);依赖安全扫描(每日 Schedule,自动修复低风险漏洞并创建 PR);文档漂移检测(每周 Schedule,比对代码变更与文档的一致性);生产告警响应(API 触发,含 curl 请求示例和 Slack 通知格式);每日 PR 摘要(含超时 PR 的 @mention 提醒);发布后烟雾测试(CD 流水线调用,健康检查 + 错误率验证)。含写好 Routine Prompt 的 5 个核心原则。2026/5/12