Communitygithub.com

nuxt4-patterns

Nuxt 4 应用模式:包含水合安全、性能优化、路由规则、懒加载以及使用 useFetch 和 useAsyncData 进行 SSR 安全的数据获取。适用于构建或审查 Nuxt 4 应用,或调试水合不匹配和 SSR 安全数据获取场景。

nuxt4-patterns 是什么?

该技能提供了一套全面的 Nuxt 4 应用开发最佳实践,重点解决水合不匹配、路由级渲染策略、性能优化以及数据获取等核心问题。它指导开发者使用 `useFetch` 和 `useAsyncData` 等组合式 API 实现 SSR 安全的数据获取,避免客户端重复请求;通过 `routeRules` 配置灵活的渲染策略(如预渲染、SWR、ISR 和客户端渲染);并利用懒加载和懒水合技术提升应用性能。该技能适用于所有 Nuxt 4 项目,支持在构建新应用或审查现有代码时使用,帮助开发者避免常见陷阱,如 SSR 中的非确定性状态或 URL 片段引起的水合问题。通过遵循这些模式,开发者能够构建出高性能、SEO 友好且用户体验流畅的全栈应用。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/nuxt4-patterns

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Nuxt 4 模式

适用于构建或调试使用了 SSR、混合渲染、路由规则或页面级数据获取的 Nuxt 4 应用。

何时激活

  • 服务器 HTML 与客户端状态之间的水合不匹配
  • 路由级渲染决策,如预渲染、SWR、ISR 或仅客户端部分
  • 围绕懒加载、懒水合或负载大小的性能优化工作
  • 使用 useFetch、useAsyncData 或 $fetch 进行页面或组件数据获取
  • 与路由参数、中间件或 SSR/客户端差异相关的 Nuxt 路由问题

水合安全

  • 保持首次渲染确定性。不要将 Date.now()、Math.random()、浏览器专用 API 或存储读取直接放入 SSR 渲染的模板状态中。
  • 当服务器无法产生相同标记时,将浏览器专用逻辑移至 onMounted()、import.meta.client、ClientOnly 或 .client.vue 组件之后。
  • 使用 Nuxt 的 useRoute() 组合式函数,而不是来自 vue-router 的。
  • 不要使用 route.fullPath 驱动 SSR 渲染的标记。URL 片段是客户端专用的,这可能会造成水合不匹配。
  • 将 ssr: false 视为真正仅浏览器区域的逃生舱口,而不是解决不匹配问题的默认修复方案。

数据获取

  • 在页面和组件中,优先使用 await useFetch() 进行 SSR 安全的 API 读取。它会将服务器获取的数据转发到 Nuxt 负载中,并避免在水合时进行第二次获取。
  • 当获取器不是简单的 $fetch() 调用、需要自定义 key 或需要组合多个异步来源时,使用 useAsyncData()。
  • 为 useAsyncData() 提供一个稳定的 key,以实现缓存重用和可预测的刷新行为。
  • 保持 useAsyncData() 处理程序无副作用。它们可以在 SSR 和水合期间运行。
  • 对于用户触发的写入或仅客户端操作,使用 $fetch(),而不是用于应从 SSR 水合的顶级页面数据。
  • 对于不应阻塞导航的非关键数据,使用 lazy: true、useLazyFetch() 或 useLazyAsyncData()。在 UI 中处理 status === 'pending'。
  • 仅对 SEO 或首次绘制不需要的数据使用 server: false。
  • 使用 pick 修剪负载大小,并在不需要深度响应式时优先使用较浅的负载。
const route = useRoute()

const { data: article, status, error, refresh } = await useAsyncData(
  () => `article:${route.params.slug}`,
  () => $fetch(`/api/articles/${route.params.slug}`),
)

const { data: comments } = await useFetch(`/api/articles/${route.params.slug}/comments`, {
  lazy: true,
  server: false,
})

路由规则

在 nuxt.config.ts 中优先使用 routeRules 配置渲染和缓存策略:

export default defineNuxtConfig({
  routeRules: {
    '/': { prerender: true },
    '/products/**': { swr: 3600 },
    '/blog/**': { isr: true },
    '/admin/**': { ssr: false },
    '/api/**': { cache: { maxAge: 60 * 60 } },
  },
})
  • prerender:构建时生成静态 HTML
  • swr:提供缓存内容并在后台重新验证
  • isr:在支持的平台上进行增量静态再生
  • ssr: false:客户端渲染的路由
  • cache 或 redirect:Nitro 级别的响应行为

按路由组选择路由规则,而非全局应用。营销页面、目录、仪表板和 API 通常需要不同的策略。

懒加载与性能

  • Nuxt 已经按路由自动进行代码拆分。在对组件拆分进行微优化之前,请确保路由边界有意义。
  • 使用 Lazy 前缀动态导入非关键组件。
  • 使用 v-if 条件性地渲染懒加载组件,以便仅在 UI 实际需要时才加载代码块。
  • 对首屏以下或非关键的交互式 UI 使用懒水合。
<template>
  <LazyRecommendations v-if="showRecommendations" />
  <LazyProductGallery hydrate-on-visible />
</template>
  • 对于自定义策略,使用 defineLazyHydrationComponent() 配合可见性或空闲策略。
  • Nuxt 的懒水合适用于单文件组件。向懒水合组件传递新属性将立即触发水合。
  • 使用 NuxtLink 进行内部导航,以便 Nuxt 可以预取路由组件和生成的负载。

审查清单

  • 首次 SSR 渲染和水合后的客户端渲染产生相同的标记
  • 页面数据使用 useFetch 或 useAsyncData,而不是顶层的 $fetch
  • 非关键数据是懒加载的,并有明确的加载 UI
  • 路由规则匹配页面的 SEO 和新鲜度要求
  • 大型交互组件被懒加载或懒水合

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

相关技能