实战

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 命令行工具开发实战:用 AI 快速构建专业 CLI 工具Claude Code 辅助命令行工具(CLI)开发的完整实战指南:Python Click/Typer、Go Cobra、Rust Clap 技术栈选型、用 Claude Code 生成完整 CLI 项目结构(参数解析/子命令/全局选项)、交互式提示和彩色输出、配置文件管理、Shell 自动补全生成、跨平台打包(PyInstaller/goreleaser),以及发布到 PyPI/npm/Homebrew 的完整流程。2026/3/26实战Claude Code Django 实战完全指南:从模型设计到 REST API 开发全流程Claude Code 辅助 Django 开发的完整实战指南:用 Claude Code 生成 Django 项目结构和 Models(含迁移文件)、Django REST Framework(DRF)API 开发(Serializer/ViewSet/Router)、用户认证系统(JWT/Session/第三方登录)、Django ORM 查询优化(select_related/prefetch_related/annotate)、异步任务(Celery + Redis)、测试用例生成(pytest-django)、Docker 化部署,以及在现有 Django 项目中快速定位和修复 Bug 的 Prompt 技巧。2026/3/26实战Claude Code Rust 实战完全指南:从所有权错误到高性能系统编程Claude Code 辅助 Rust 开发的完整实战指南:用 Claude Code 理解 Rust 所有权(ownership)、借用(borrow)和生命周期(lifetime)报错、生成符合 Rust 惯用法的代码(使用 Result/Option/迭代器)、借助 Claude Code 快速上手异步 Rust(Tokio/async-await)、实战案例(CLI 工具/HTTP 客户端/WebAssembly 模块/系统命令行工具)、Cargo.toml 依赖管理优化、unsafe Rust 代码的安全审查、Rust 与 Python/Go 代码互操作,以及最有价值的 Rust Prompt 模板。2026/3/26实战OpenClaw 与 Claude Code 协同使用实战:AI 聊天助手 + AI 编程助手的终极组合OpenClaw 与 Claude Code 协同使用的完整实战指南:两款工具的定位差异(OpenClaw=聊天AI助手框架,Claude Code=代码库直接操作的编程工具)、在 OpenClaw 中通过 exec 工具调用 Claude Code CLI(claude 命令)执行编程任务、把 OpenClaw 的 Telegram 消息转化为 Claude Code 任务(用自然语言描述→Claude Code执行→返回结果)、使用 OpenClaw Cron 定期触发 Claude Code 执行代码审查/依赖更新/测试/文档生成、CRS 代理在两者中的统一接入方案,以及常见的协同架构模式(主动触发/被动响应/定时执行)。2026/3/24实战Claude Code + NestJS 实战:用 AI 构建企业级 TypeScript 后端服务Claude Code 与 NestJS 框架深度协作实战:模块化架构设计(Module/Controller/Service/Provider)、让 Claude 生成符合 NestJS 惯例的 CRUD 模块、依赖注入系统的 AI 辅助使用、Guards 认证守卫(JWT/Role-based)、Interceptors 全局日志与请求变换、Pipes 数据验证(class-validator)、Exception Filters 统一异常处理、TypeORM 集成与数据库迁移、Swagger 文档自动生成,以及 NestJS 微服务(Microservices)架构入门。2026/3/21