nuxt4-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNuxt 4 Patterns
Nuxt 4 应用模式
Use when building or debugging Nuxt 4 apps with SSR, hybrid rendering, route rules, or page-level data fetching.
适用于构建或调试采用SSR、混合渲染、路由规则或页面级数据获取的Nuxt 4应用时使用。
When to Activate
适用场景
- Hydration mismatches between server HTML and client state
- Route-level rendering decisions such as prerender, SWR, ISR, or client-only sections
- Performance work around lazy loading, lazy hydration, or payload size
- Page or component data fetching with ,
useFetch, oruseAsyncData$fetch - Nuxt routing issues tied to route params, middleware, or SSR/client differences
- 服务器端HTML与客户端状态之间的水合不匹配问题
- 路由级别的渲染决策,如预渲染(prerender)、SWR、ISR或仅客户端渲染区域
- 围绕懒加载、延迟水合或 payload 大小的性能优化工作
- 使用、
useFetch或useAsyncData进行页面或组件的数据获取$fetch - 与路由参数、中间件或SSR/客户端差异相关的Nuxt路由问题
Hydration Safety
水合安全性
- Keep the first render deterministic. Do not put ,
Date.now(), browser-only APIs, or storage reads directly into SSR-rendered template state.Math.random() - Move browser-only logic behind ,
onMounted(),import.meta.client, or aClientOnlycomponent when the server cannot produce the same markup..client.vue - Use Nuxt's composable, not the one from
useRoute().vue-router - Do not use to drive SSR-rendered markup. URL fragments are client-only, which can create hydration mismatches.
route.fullPath - Treat as an escape hatch for truly browser-only areas, not a default fix for mismatches.
ssr: false
- 确保首次渲染的确定性。不要将、
Date.now()、仅浏览器可用的API或存储读取操作直接放入SSR渲染的模板状态中。Math.random() - 当服务器无法生成相同标记时,将仅浏览器逻辑移至、
onMounted()、import.meta.client组件或ClientOnly组件中。.client.vue - 使用Nuxt提供的组合式函数,而非
useRoute()中的同名函数。vue-router - 不要使用来驱动SSR渲染的标记。URL片段仅在客户端可用,这可能导致水合不匹配。
route.fullPath - 将视为纯浏览器区域的应急方案,而非解决不匹配问题的默认方法。
ssr: false
Data Fetching
数据获取
- Prefer for SSR-safe API reads in pages and components. It forwards server-fetched data into the Nuxt payload and avoids a second fetch on hydration.
await useFetch() - Use when the fetcher is not a simple
useAsyncData()call, when you need a custom key, or when you are composing multiple async sources.$fetch() - Give a stable key for cache reuse and predictable refresh behavior.
useAsyncData() - Keep handlers side-effect free. They can run during SSR and hydration.
useAsyncData() - Use for user-triggered writes or client-only actions, not top-level page data that should be hydrated from SSR.
$fetch() - Use ,
lazy: true, oruseLazyFetch()for non-critical data that should not block navigation. HandleuseLazyAsyncData()in the UI.status === 'pending' - Use only for data that is not needed for SEO or the first paint.
server: false - Trim payload size with and prefer shallower payloads when deep reactivity is unnecessary.
pick
ts
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,
})- 在页面和组件中优先使用进行SSR安全的API读取。它会将服务器端获取的数据转发到Nuxt payload中,避免水合时再次获取数据。
await useFetch() - 当数据获取逻辑不是简单的调用、需要自定义key或组合多个异步数据源时,使用
$fetch()。useAsyncData() - 为设置稳定的key,以实现缓存复用和可预测的刷新行为。
useAsyncData() - 保持的处理函数无副作用。它们可能会在SSR和水合过程中运行。
useAsyncData() - 使用处理用户触发的写入操作或仅客户端的操作,而非用于需要从SSR水合的顶级页面数据。
$fetch() - 对于不需要阻塞导航的非关键数据,使用、
lazy: true或useLazyFetch()。在UI中处理useLazyAsyncData()状态。status === 'pending' - 仅当数据不需要用于SEO或首次绘制时,才使用。
server: false - 使用方法精简payload大小,当不需要深度响应式时,优先使用结构更扁平的payload。
pick
ts
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,
})Route Rules
路由规则
Prefer in for rendering and caching strategy:
routeRulesnuxt.config.tsts
export default defineNuxtConfig({
routeRules: {
'/': { prerender: true },
'/products/**': { swr: 3600 },
'/blog/**': { isr: true },
'/admin/**': { ssr: false },
'/api/**': { cache: { maxAge: 60 * 60 } },
},
})- : static HTML at build time
prerender - : serve cached content and revalidate in the background
swr - : incremental static regeneration on supported platforms
isr - : client-rendered route
ssr: false - or
cache: Nitro-level response behaviorredirect
Pick route rules per route group, not globally. Marketing pages, catalogs, dashboards, and APIs usually need different strategies.
优先在中使用配置渲染和缓存策略:
nuxt.config.tsrouteRulests
export default defineNuxtConfig({
routeRules: {
'/': { prerender: true },
'/products/**': { swr: 3600 },
'/blog/**': { isr: true },
'/admin/**': { ssr: false },
'/api/**': { cache: { maxAge: 60 * 60 } },
},
})- : 构建时生成静态HTML
prerender - : 提供缓存内容并在后台重新验证
swr - : 在支持的平台上进行增量静态再生
isr - : 客户端渲染路由
ssr: false - 或
cache: Nitro级别的响应行为redirect
为每个路由组选择合适的路由规则,而非全局统一配置。营销页面、商品目录、仪表板和API通常需要不同的策略。
Lazy Loading and Performance
懒加载与性能优化
- Nuxt already code-splits pages by route. Keep route boundaries meaningful before micro-optimizing component splits.
- Use the prefix to dynamically import non-critical components.
Lazy - Conditionally render lazy components with so the chunk is not loaded until the UI actually needs it.
v-if - Use lazy hydration for below-the-fold or non-critical interactive UI.
vue
<template>
<LazyRecommendations v-if="showRecommendations" />
<LazyProductGallery hydrate-on-visible />
</template>- For custom strategies, use with a visibility or idle strategy.
defineLazyHydrationComponent() - Nuxt lazy hydration works on single-file components. Passing new props to a lazily hydrated component will trigger hydration immediately.
- Use for internal navigation so Nuxt can prefetch route components and generated payloads.
NuxtLink
- Nuxt已经按路由进行代码分割。在对组件分割进行微优化之前,先确保路由边界的合理性。
- 使用前缀动态导入非关键组件。
Lazy - 结合条件渲染懒加载组件,确保代码块仅在UI实际需要时才加载。
v-if - 对首屏以下或非关键的交互式UI使用延迟水合。
vue
<template>
<LazyRecommendations v-if="showRecommendations" />
<LazyProductGallery hydrate-on-visible />
</template>- 对于自定义策略,使用并结合可见性或空闲状态策略。
defineLazyHydrationComponent() - Nuxt的延迟水合功能适用于单文件组件。向延迟水合的组件传递新props会立即触发水合。
- 使用进行内部导航,以便Nuxt可以预取路由组件和生成的payload。
NuxtLink
Review Checklist
检查清单
- First SSR render and hydrated client render produce the same markup
- Page data uses or
useFetch, not top-leveluseAsyncData$fetch - Non-critical data is lazy and has explicit loading UI
- Route rules match the page's SEO and freshness requirements
- Heavy interactive islands are lazy-loaded or lazily hydrated
- SSR首次渲染和水合后的客户端渲染生成相同的标记
- 页面数据使用或
useFetch,而非顶级useAsyncData$fetch - 非关键数据采用懒加载方式,并配有明确的加载状态UI
- 路由规则与页面的SEO和内容新鲜度需求匹配
- 大型交互式独立区块采用懒加载或延迟水合