Communitygithub.com

Nuxt 4 模式

針對水合安全、效能、路由規則、延遲載入以及使用 useFetch 和 useAsyncData 進行 SSR 安全資料擷取的 Nuxt 4 應用程式模式。在建立或審查 Nuxt 4 應用程式,或除錯水合不一致及 SSR 安全資料擷取時使用。

Nuxt 4 模式 是什麼?

此技能提供了一套全面的 Nuxt 4 應用程式模式與最佳實踐,專注於水合安全、資料擷取、路由規則、延遲載入和效能最佳化。它指導開發人員如何避免因伺服器 HTML 與客戶端狀態不一致而導致的水合錯誤,例如避免直接在 SSR 渲染的模板中使用 `Date.now()` 或瀏覽器專用 API,並推廣使用 `onMounted()` 或 `ClientOnly` 元件。在資料擷取方面,它強調了在頁面和元件中使用 `await useFetch()` 進行 SSR 安全 API 讀取的優勢,因為這可以將伺服器擷取的資料轉發到 Nuxt payload 中,從而在水合時避免再次擷取。它還詳細說明了何時使用 `useAsyncData()`、如何透過 `lazy: true` 或 `useLazyFetch()` 處理非關鍵資料,以及如何使用 `pick` 選項縮減 payload 大小。該技能還涵蓋了 `nuxt.config.ts` 中的 `routeRules`,以定義預渲染、SWR、ISR 和客戶端渲染路由的策略,以及透過 `Lazy` 前綴和 `defineLazyHydrationComponent()` 進行延遲載入和延遲水合的技術。最後,它提供了一個審查清單,以確保資料擷取、路由規則和互動島嶼符合 SEO 和效能要求。此技能適用於所有支援自訂技能的 AI 代理平台,如 Claude Code、Cursor 和 Codex。

相容平台~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 或純客戶端區塊相關的路由層級渲染決策
  • 關於延遲載入、延遲水合或 payload 大小的效能工作
  • 使用 useFetch、useAsyncData 或 $fetch 進行頁面或元件資料擷取
  • 與路由參數、中介軟體或 SSR/客戶端差異相關的 Nuxt 路由問題

水合安全

  • 保持首次渲染的確定性。不要將 Date.now()、Math.random()、瀏覽器專用 API 或儲存體讀取直接放入 SSR 渲染的模板狀態中。
  • 當伺服器無法產生相同標記時,將瀏覽器專用邏輯移至 onMounted()、import.meta.client、ClientOnly 或 .client.vue 元件的後方。
  • 使用 Nuxt 的 useRoute() composable,而不是 vue-router 的。
  • 不要使用 route.fullPath 來驅動 SSR 渲染的標記。URL 片段是僅限客戶端的,這可能會產生水合不一致。
  • 將 ssr: false 視為真正僅限瀏覽器區域的逃生艙口,而不是修補不一致的預設解決方案。

資料擷取

  • 在頁面和元件中,優先使用 await useFetch() 進行 SSR 安全的 API 讀取。它會將伺服器擷取的資料轉發到 Nuxt payload 中,並避免在水合時進行第二次擷取。
  • 當擷取器不是簡單的 $fetch() 呼叫、需要自訂鍵或正在組合多個非同步來源時,使用 useAsyncData()。
  • 為 useAsyncData() 提供一個穩定的鍵,以便進行快取重用和可預測的重新整理行為。
  • 保持 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 實際需要時才載入 chunk。
  • 對摺疊以下或非關鍵的互動式 UI 使用延遲水合。
<template>
  <LazyRecommendations v-if="showRecommendations" />
  <LazyProductGallery hydrate-on-visible />
</template>
  • 對於自訂策略,使用 defineLazyHydrationComponent() 搭配可見性或空閒策略。
  • Nuxt 的延遲水合適用於單一檔案元件。向延遲水合的元件傳遞新 prop 將立即觸發水合。
  • 使用 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/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.

相關技能