Nuxt: 项目开发
最后更新:2026-08-26
设计完成后,Charlie 带领团队开始编码。认证模块先上——没有登录一切免谈。然后是商品模块——百万级商品的 CRUD 与 ISR 缓存。购物车和订单紧跟其后。Alice 测试消费者流程,Bob 验证管理功能,每个模块都经过端到端测试。
1. 你将学到
- 认证模块:OAuth2 + JWT + auth 中间件 + 角色权限
- 商品模块:百万级 CRUD + ISR 缓存 + SEO + 搜索筛选
- 购物车模块:Pinia Store + Composable + server API + 库存校验
- 订单模块:Prisma 事务 + 状态机 + Stripe 支付
- 国际化与性能:i18n 三语 + @nuxt/image + Lighthouse 审计
2. 一个团队的真实故事
(1) 痛点:设计图落不了地
Charlie 有完整的设计文档,但团队不知道先做什么后做什么。Alice 写了商品页面但购物车还没 API,Bob 写了管理后台但认证还没做好。模块之间互相等待,进度卡住。
(2) 按模块渐进开发的解法
按依赖顺序逐模块开发:认证 → 商品 → 购物车 → 订单 → 国际化。每个模块完成后立即测试,不依赖未完成的模块。
(3) 收益:稳步推进
每个模块 3-5 天完成,2 周内核心功能全部上线,Alice 可以跑通完整购物流程。
3. 开发里程碑
(1) 模块开发甘特图
gantt
title MegaShop Development Milestones
dateFormat YYYY-MM-DD
section Auth Module
JWT + OAuth2 :a1, 2026-01-01, 3d
Auth Middleware :a2, after a1, 2d
section Product Module
CRUD API :p1, after a2, 3d
Search + Filter :p2, after p1, 2d
ISR Cache :p3, after p2, 1d
section Cart Module
Store + API :c1, after a2, 3d
Composable :c2, after c1, 1d
section Order Module
Prisma Transaction :o1, after c1, 3d
Stripe Payment :o2, after o1, 2d
section i18n + Perf
Three Languages :i1, after p3, 2d
Image Optimization :i2, after i1, 1d
Lighthouse Audit :i3, after i2, 1d
4. 认证模块
▶ 示例:JWT 工具 + 注册/登录 API
TYPESCRIPT
// server/utils/jwt.ts
import jwt from 'jsonwebtoken'
const config = useRuntimeConfig()
export function signTokenPair(payload: { userId: number; email: string; role: string }) {
return {
accessToken: jwt.sign(payload, config.jwtAccessSecret, { expiresIn: '15m' }),
refreshToken: jwt.sign(payload, config.jwtRefreshSecret, { expiresIn: '7d' })
}
}
export function setAuthCookies(event: any, tokens: { accessToken: string; refreshToken: string }) {
setCookie(event, 'access-token', tokens.accessToken, { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 900 })
setCookie(event, 'refresh-token', tokens.refreshToken, { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 604800 })
}
输出:
TEXT
📖 仅展示
// 执行成功
TYPESCRIPT
// server/api/auth/register.post.ts
export default defineEventHandler(async (event) => {
const { email, password, name } = await readBody(event)
const existing = await prisma.user.findUnique({ where: { email } })
if (existing) throw createError({ statusCode: 409, message: 'Email already registered' })
const hashedPassword = await hashPassword(password)
const user = await prisma.user.create({
data: { email, name, password: hashedPassword, role: 'CUSTOMER' }
})
const tokens = signTokenPair({ userId: user.id, email: user.email, role: user.role })
setAuthCookies(event, tokens)
return { user: { id: user.id, email: user.email, name: user.name, role: user.role } }
})
5. 商品模块
▶ 示例:商品 CRUD API(Prisma + Cache)
TYPESCRIPT
// server/api/products/index.get.ts
export default cachedEventHandler(
async (event) => {
const { page = '1', limit = '20', category, search, sort } = getQuery(event)
const where = {
AND: [
category ? { category: { slug: category as string } } : {},
search ? { OR: [
{ name: { contains: search as string, mode: 'insensitive' } },
{ description: { contains: search as string, mode: 'insensitive' } }
]} : {}
]
}
const orderBy = sort === 'price-asc' ? { price: 'asc' }
: sort === 'price-desc' ? { price: 'desc' }
: { createdAt: 'desc' }
const [items, total] = await Promise.all([
prisma.product.findMany({
where, orderBy,
skip: (Number(page) - 1) * Number(limit),
take: Number(limit),
include: { category: { select: { name: true, slug: true } } }
}),
prisma.product.count({ where })
])
return { items, total, page: Number(page), limit: Number(limit) }
},
{ maxAge: 60, swr: true, getKey: (event) => `products:${getRequestURL(event).search}` }
)
输出:
TEXT
📖 仅展示
// 执行成功
▶ 示例:商品详情 + SEO
VUE
<!-- pages/products/[id].vue -->
<template>
<div v-if="product">
<h1>{{ product.name }}</h1>
<p>{{ formatFromUSD(product.price) }}</p>
<button @click="handleAddToCart">{{ t('product.addToCart') }}</button>
</div>
</template>
<script setup lang="ts">
const route = useRoute()
const config = useRuntimeConfig()
const { t } = useI18n()
const { formatFromUSD } = useLocalizedPrice()
const { addToCart } = useCart()
const { data: product } = await useFetch(`/api/products/${route.params.id}`)
// Dynamic SEO per product
useSeoMeta({
title: () => `${product.value?.name} - MegaShop`,
description: () => `Buy ${product.value?.name} - $${product.value?.price} USD`,
ogTitle: () => product.value?.name,
ogImage: () => product.value?.image,
ogType: 'product'
})
// JSON-LD structured data
useHead({ script: [{ type: 'application/ld+json', innerHTML: computed(() => JSON.stringify({
'@context': 'https://schema.org', '@type': 'Product',
name: product.value?.name,
offers: { '@type': 'Offer', priceCurrency: 'USD', price: product.value?.price }
}))}]})
async function handleAddToCart() {
if (product.value) await addToCart(product.value.id, product.value.name)
}
</script>
输出:
TEXT
📖 仅展示
// 执行成功
6. 购物车模块
▶ 示例:cartStore + useCart
TYPESCRIPT
// stores/cart.ts
export const useCartStore = defineStore('cart', () => {
const items = ref<CartItem[]>([])
const totalItems = computed(() => items.value.reduce((s, i) => s + i.quantity, 0))
const totalPrice = computed(() => items.value.reduce((s, i) => s + i.price * i.quantity, 0))
async function addItem(productId: number) {
const cart = await $fetch('/api/cart/add', { method: 'POST', body: { productId } })
items.value = cart.items
}
async function removeItem(productId: number) {
const cart = await $fetch('/api/cart/remove', { method: 'DELETE', body: { productId } })
items.value = cart.items
}
async function fetchCart() {
const cart = await $fetch('/api/cart')
items.value = cart.items || []
}
return { items, totalItems, totalPrice, addItem, removeItem, fetchCart }
})
输出:
TEXT
📖 仅展示
// 执行成功
▶ 示例:购物车 API(带库存校验)
TYPESCRIPT
// server/api/cart/add.post.ts
export default defineEventHandler(async (event) => {
const userId = event.context.user?.id
const { productId, quantity = 1 } = await readBody(event)
// Check stock
const product = await prisma.product.findUnique({ where: { id: productId } })
if (!product?.inStock) throw createError({ statusCode: 400, message: 'Product out of stock' })
// Upsert cart item
await prisma.cartItem.upsert({
where: { userId_productId: { userId, productId } },
update: { quantity: { increment: quantity } },
create: { userId, productId, quantity }
})
const cart = await prisma.cartItem.findMany({
where: { userId },
include: { product: { select: { name: true, price: true, image: true } } }
})
const total = cart.reduce((s, i) => s + Number(i.product.price) * i.quantity, 0)
return { items: cart, total }
})
输出:
TEXT
📖 仅展示
// 执行成功
7. 订单模块
▶ 示例:订单创建事务
TYPESCRIPT
// server/api/orders/index.post.ts
export default defineEventHandler(async (event) => {
const userId = event.context.user?.id
if (!userId) throw createError({ statusCode: 401, message: 'Login required' })
const order = await prisma.$transaction(async (tx) => {
// Get cart items
const cartItems = await tx.cartItem.findMany({
where: { userId },
include: { product: true }
})
if (cartItems.length === 0) {
throw createError({ statusCode: 400, message: 'Cart is empty' })
}
// Check stock for all items
for (const item of cartItems) {
if (!item.product.inStock) {
throw createError({ statusCode: 400, message: `${item.product.name} out of stock` })
}
}
// Calculate total
const total = cartItems.reduce((sum, item) => sum + Number(item.product.price) * item.quantity, 0)
// Create order with items
const newOrder = await tx.order.create({
data: {
userId,
total,
status: 'PENDING',
items: {
create: cartItems.map(item => ({
productId: item.productId,
quantity: item.quantity,
price: item.product.price
}))
}
},
include: { items: { include: { product: true } } }
})
// Clear cart
await tx.cartItem.deleteMany({ where: { userId } })
return newOrder
})
return { order, message: 'Order created' }
})
输出:
TEXT
📖 仅展示
// 执行成功
8. 国际化与性能
▶ 示例:nuxt.config.ts 完整生产配置
TYPESCRIPT
// nuxt.config.ts
export default defineNuxtConfig({
ssr: true,
modules: [
'@pinia/nuxt',
'@nuxtjs/tailwindcss',
'@nuxtjs/i18n',
'@nuxtjs/sitemap',
'@nuxt/image',
'~/modules/analytics'
],
app: {
head: {
title: 'MegaShop',
titleTemplate: '%s | MegaShop',
meta: [
{ name: 'description', content: 'Over 1 million products shipped worldwide' }
]
}
},
i18n: {
locales: [
{ code: 'en', name: 'English', file: 'en.json', currency: 'USD' },
{ code: 'zh', name: '中文', file: 'zh.json', currency: 'CNY' },
{ code: 'ja', name: '日本語', file: 'ja.json', currency: 'JPY' }
],
defaultLocale: 'en',
lazy: true,
langDir: 'locales/',
strategy: 'prefix_except_default'
},
image: {
quality: 80,
format: ['webp', 'avif']
},
sitemap: {
hostname: 'https://megashop.com',
gzip: true
},
runtimeConfig: {
databaseUrl: process.env.DATABASE_URL,
redisUrl: process.env.REDIS_URL,
jwtAccessSecret: process.env.JWT_ACCESS_SECRET,
jwtRefreshSecret: process.env.JWT_REFRESH_SECRET,
public: {
apiBase: process.env.API_BASE || '/api',
siteUrl: process.env.SITE_URL || 'https://megashop.com',
stripePublishableKey: process.env.STRIPE_PUBLISHABLE_KEY
}
},
routeRules: {
'/': { prerender: true },
'/about': { prerender: true },
'/products': { swr: 3600 },
'/products/**': { swr: 86400 },
'/categories/**': { swr: 21600 },
'/admin/**': { ssr: false },
'/cart': { ssr: false },
'/checkout': { ssr: false },
'/profile/**': { ssr: false },
'/api/**': { cors: true },
'/_nuxt/**': { headers: { 'cache-control': 'public, max-age=31536000, immutable' } }
},
nitro: {
preset: process.env.DEPLOY_TARGET || 'node-server',
storage: {
products: { driver: process.env.NODE_ENV === 'production' ? 'redis' : 'memory' }
}
},
components: [{ path: '~/components', pathPrefix: false }]
})
输出:
TEXT
📖 仅展示
// 执行成功
❓ 常见问题
Q 模块开发顺序重要吗?
A 非常重要。认证必须先做(其他模块依赖登录态),商品其次(购物车/订单依赖商品数据),最后做国际化(不影响核心功能)。
Q 每个模块大概要写多少代码?
A 认证模块 ~500 行、商品模块 ~800 行、购物车 ~400 行、订单 ~500 行、国际化 ~200 行。加上配置和测试,总计约 3000-4000 行。
Q 怎么保证模块之间的 API 契约?
A 用 TypeScript 接口定义 API 请求/响应类型,放在 shared/types.ts 中。前后端共享类型定义,编译时检查一致性。
Q 开发时 mock 数据怎么过渡到 Prisma?
A API 接口格式保持不变,只替换内部实现。从 mock 数组改为 prisma.findMany(),路由和响应格式不变。
Q Stripe 支付怎么测试?
A 用 Stripe 测试密钥 + 测试卡号(4242 4242 4242 4242)。永远不会真实扣款。上线前切换到生产密钥。
Q i18n 翻译什么时候做?
A 核心功能完成后再做 i18n。先写死英文文本,功能稳定后提取为翻译 key。过早 i18n 会增加开发复杂度。
📖 小节
- 按依赖顺序开发:认证 → 商品 → 购物车 → 订单 → 国际化
- 认证模块:JWT 双令牌 + httpOnly Cookie + auth 中间件 + admin 角色检查
- 商品模块:Prisma CRUD + Nitro 缓存 + ISR + SEO meta + JSON-LD
- 购物车:Pinia Store + useCart Composable + 库存校验
- 订单:Prisma 事务保证原子性 + Stripe 支付集成
📝 作业
- 基础题(难度⭐):实现认证模块(注册/登录/刷新令牌),验证 Cookie 正确设置
- 进阶题(难度⭐⭐):实现商品 CRUD + 购物车 + 结算的完整流程,端到端可运行
- 挑战题(难度⭐⭐⭐):完成 MegaShop 全部核心模块 + i18n + 性能优化,Lighthouse 评分 90+
---|