Communitygithub.com

Nuxt 4 模式

用於水合安全、效能、路由規則、懶加載以及使用 useFetch 和 useAsyncData 進行 SSR 安全資料擷取的 Nuxt 4 應用模式。在構建或審查 Nuxt 4 應用程式,或偵錯水合不匹配和 SSR 安全資料擷取時使用。

Nuxt 4 模式 是什麼?

這項技能提供了 Nuxt 4 應用程式的全面模式,重點在於水合安全性、效能最佳化、路由規則、懶加載以及 SSR 安全的資料擷取。它適用於使用伺服器端渲染 (SSR)、混合渲染或頁面級資料擷取的開發者。該技能包含避免水合不匹配的指南(例如保持首個渲染結果確定性、使用 `onMounted` 或 `ClientOnly` 處理僅用於瀏覽器的邏輯),以及透過 `useFetch` 和 `useAsyncData` 進行最佳資料擷取的策略,以確保在 SSR 期間取得的資料不會在客戶端重新擷取。它還涵蓋了在 `nuxt.config.ts` 中透過 `routeRules` 配置路由級渲染(如 `prerender`、`swr`、`isr`)的方法,以及使用 `Lazy` 前綴元件進行程式碼拆分和懶加載的效能最佳化技術。此技能支援 Claude Code、Cursor 和 Codex 等 AI 代理平台,幫助開發者偵錯水合問題、改善頁面載入時間,並為 Nuxt 4 應用實施正確的資料擷取模式。

相容平台~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 或僅限用戶端的區塊
  • 圍繞懶加載、懶水合或有效負載大小的效能最佳化工作
  • 使用 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 視為僅用於瀏覽器區域的應急方案,而不是解決不匹配問題的預設方法。

資料擷取

  • 對於頁面和元件中的 SSR 安全 API 讀取,建議使用 await useFetch()。它將伺服器擷取的資料轉發到 Nuxt 有效負載中,並避免在水合時進行第二次擷取。
  • 當獲取器不是簡單的 $fetch() 呼叫、需要自訂鍵或組合多個非同步來源時,請使用 useAsyncData()。
  • 為 useAsyncData() 提供一個穩定的鍵,以實現快取重用和可預測的重新整理行為。
  • 保持 useAsyncData() 處理程序無副作用。它們可以在 SSR 和水合期間執行。
  • 對於使用者觸發的寫入或僅限用戶端的操作,請使用 $fetch(),而不是應從 SSR 水合的頂層頁面資料。
  • 對於不應阻塞導航的非關鍵資料,請使用 lazy: true、useLazyFetch() 或 useLazyAsyncData()。在使用者介面中處理 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 條件渲染懶加載元件,以便僅在使用者介面實際需要時才載入程式碼區塊。
  • 對摺疊以下或非關鍵的互動式使用者介面使用懶水合。
<template>
  <LazyRecommendations v-if="showRecommendations" />
  <LazyProductGallery hydrate-on-visible />
</template>
  • 對於自訂策略,請使用帶有可見性或空閒策略的 defineLazyHydrationComponent()。
  • Nuxt 懶水合適用於單檔案元件。向懶水合元件傳遞新 props 會立即觸發水合。
  • 使用 NuxtLink 進行內部導航,以便 Nuxt 可以預取路由元件和生成的有效負載。

審查清單

  • 首個 SSR 渲染和水合後的客戶端渲染產生相同的標記
  • 頁面資料使用 useFetch 或 useAsyncData,而不是頂層的 $fetch
  • 非關鍵資料是懶加載的,並且有明確的載入使用者介面
  • 路由規則符合頁面的 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.

相關技能