nuxt4-patterns by affaan-m/everything-claude-code
npx skills add https://github.com/affaan-m/everything-claude-code --skill nuxt4-patterns在构建或调试具有 SSR、混合渲染、路由规则或页面级数据获取功能的 Nuxt 4 应用时使用。
useFetch、useAsyncData 或 $fetch 进行页面或组件数据获取时Date.now()、Math.random()、仅限浏览器的 API 或存储读取直接放入 SSR 渲染的模板状态中。onMounted()、import.meta.client、ClientOnly 或 组件之后。广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
.client.vueuseRoute() 组合式函数,而不是 vue-router 中的那个。route.fullPath 来驱动 SSR 渲染的标记。URL 片段仅限客户端,这可能导致水合不匹配。ssr: false 视为真正仅限浏览器区域的逃生舱口,而不是解决不匹配问题的默认修复方法。await useFetch()。它将服务器获取的数据转发到 Nuxt 有效负载中,并避免在水合时进行第二次获取。$fetch() 调用、需要自定义键或组合多个异步源时,使用 useAsyncData()。useAsyncData() 提供一个稳定的键,以便缓存重用和可预测的刷新行为。useAsyncData() 处理程序无副作用。它们可能在 SSR 和水合期间运行。$fetch(),而不是应从 SSR 水合而来的顶级页面数据。lazy: true、useLazyFetch() 或 useLazyAsyncData()。在 UI 中处理 status === 'pending' 状态。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: 在构建时生成静态 HTMLswr: 提供缓存内容并在后台重新验证isr: 在支持的平台上进行增量静态再生ssr: false: 客户端渲染的路由cache 或 redirect: Nitro 级别的响应行为按路由组选择路由规则,而不是全局设置。营销页面、目录、仪表板和 API 通常需要不同的策略。
Lazy 前缀动态导入非关键组件。v-if 有条件地渲染懒加载组件,以便在 UI 实际需要时才加载该代码块。<template>
<LazyRecommendations v-if="showRecommendations" />
<LazyProductGallery hydrate-on-visible />
</template>
defineLazyHydrationComponent() 并配合可见性或空闲策略。NuxtLink,以便 Nuxt 可以预取路由组件和生成的有效负载。useFetch 或 useAsyncData,而不是顶级的 $fetch每周安装量
147
代码仓库
GitHub 星标数
102.1K
首次出现
4 天前
安全审计
安装于
codex139
cursor125
opencode123
gemini-cli123
github-copilot123
amp123
Use when building or debugging Nuxt 4 apps with SSR, hybrid rendering, route rules, or page-level data fetching.
useFetch, useAsyncData, or $fetchDate.now(), Math.random(), browser-only APIs, or storage reads directly into SSR-rendered template state.onMounted(), import.meta.client, ClientOnly, or a .client.vue component when the server cannot produce the same markup.useRoute() composable, not the one from vue-router.route.fullPath to drive SSR-rendered markup. URL fragments are client-only, which can create hydration mismatches.ssr: false as an escape hatch for truly browser-only areas, not a default fix for mismatches.Prefer await useFetch() 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.
Use useAsyncData() when the fetcher is not a simple $fetch() call, when you need a custom key, or when you are composing multiple async sources.
Give useAsyncData() a stable key for cache reuse and predictable refresh behavior.
Keep useAsyncData() handlers side-effect free. They can run during SSR and hydration.
Use $fetch() for user-triggered writes or client-only actions, not top-level page data that should be hydrated from SSR.
Use lazy: true, useLazyFetch(), or for non-critical data that should not block navigation. Handle in the UI.
Prefer routeRules in nuxt.config.ts for rendering and caching strategy:
export default defineNuxtConfig({
routeRules: {
'/': { prerender: true },
'/products/**': { swr: 3600 },
'/blog/**': { isr: true },
'/admin/**': { ssr: false },
'/api/**': { cache: { maxAge: 60 * 60 } },
},
})
prerender: static HTML at build timeswr: serve cached content and revalidate in the backgroundisr: incremental static regeneration on supported platformsssr: false: client-rendered routecache or redirect: Nitro-level response behaviorPick route rules per route group, not globally. Marketing pages, catalogs, dashboards, and APIs usually need different strategies.
Nuxt already code-splits pages by route. Keep route boundaries meaningful before micro-optimizing component splits.
Use the Lazy prefix to dynamically import non-critical components.
Conditionally render lazy components with v-if so the chunk is not loaded until the UI actually needs it.
Use lazy hydration for below-the-fold or non-critical interactive UI.
<template> <LazyRecommendations v-if="showRecommendations" /> <LazyProductGallery hydrate-on-visible /> </template>For custom strategies, use defineLazyHydrationComponent() with a visibility or idle strategy.
Nuxt lazy hydration works on single-file components. Passing new props to a lazily hydrated component will trigger hydration immediately.
Use NuxtLink for internal navigation so Nuxt can prefetch route components and generated payloads.
useFetch or useAsyncData, not top-level $fetchWeekly Installs
147
Repository
GitHub Stars
102.1K
First Seen
4 days ago
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex139
cursor125
opencode123
gemini-cli123
github-copilot123
amp123
Vue.js测试最佳实践:Vue 3组件、组合式函数、Pinia与异步测试完整指南
4,000 周安装
useLazyAsyncData()status === 'pending'Use server: false only for data that is not needed for SEO or the first paint.
Trim payload size with pick and prefer shallower payloads when deep reactivity is unnecessary.
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,
})