Communitygithub.com

Nuxt 4 模式

Nuxt 4 应用模式指南,涵盖水合安全、性能优化、路由规则、懒加载以及使用 useFetch 和 useAsyncData 进行 SSR 安全的数据获取。在构建或审查 Nuxt 4 应用、调试水合不匹配或 SSR 安全数据获取时使用。

Nuxt 4 模式 是什么?

该技能提供了全面的 Nuxt 4 模式指南,专注于构建健壮的 SSR 应用。它涵盖了水合安全,确保服务器端和客户端渲染输出的一致性,并提供了处理浏览器特定代码的指导。该技能详细阐述了数据获取策略,强调优先使用 `useFetch` 和 `useAsyncData` 进行 SSR 安全读取,以有效利用 Nuxt 的 payload 机制,避免重复请求。此外,它深入介绍了路由规则(`routeRules`)以灵活控制渲染和缓存策略(如预渲染、SWR、ISR 等),并展示了懒加载和性能优化技巧,包括动态导入和延迟水合。最后,它提供了一个全面的审查清单,帮助开发者确保 SSR 一致性、数据获取正确性和性能优化。该技能适用于使用 Nuxt 4 的任何项目,可运行于 Claude Code、Cursor 等 AI 编程工具,通过分析项目代码和 `nuxt.config.ts` 配置提供具体建议。

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

在你喜欢的 AI 中提问

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

文档

Nuxt 4 模式 是做什么的?

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

何时激活

  • 服务器 HTML 与客户端状态之间的水合不匹配
  • 路由级别的渲染决策,如预渲染、SWR、ISR 或仅客户端区域
  • 关于懒加载、延迟水合或 payload 大小的性能工作
  • 使用 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 payload 中,并避免在水合时进行第二次获取。
  • 当 fetcher 不是简单的 $fetch() 调用、需要自定义 key 或组合多个异步源时,使用 useAsyncData()。
  • 为 useAsyncData() 提供一个稳定的 key,以实现缓存重用和可预测的刷新行为。
  • 保持 useAsyncData() 处理函数无副作用。它们可能同时在 SSR 和水合期间运行。
  • 为用户触发的写入或仅客户端操作使用 $fetch(),不要用于应从 SSR 水合的顶层页面数据。
  • 对于不应阻塞导航的非关键数据,使用 lazy: true、useLazyFetch() 或 useLazyAsyncData()。在 UI 中处理 status === 'pending' 状态。
  • 仅对 SEO 或首屏不需要的数据使用 server: false。
  • 使用 pick 精简 payload 大小,当深层响应式不是必需时,优先使用较浅的 payload。
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 可以预取路由组件和生成的 payload。

审查清单

  • 首次 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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相关技能