components

components/ 目录是放置所有 Vue 组件的地方。

Nuxt 会自动导入此目录中的任何组件(以及你可能使用的任何模块注册的组件)。

目录结构
-| components/
---| AppHeader.vue
---| AppFooter.vue
app.vue
<template>
  <div>
    <AppHeader />
    <NuxtPage />
    <AppFooter />
  </div>
</template>

组件名称

如果你在嵌套目录中有组件,例如:

目录结构
-| components/
---| base/
-----| foo/
-------| Button.vue

... 那么组件的名称将基于其自身的路径目录和文件名,重复的段会被移除。因此,组件的名称将是:

<BaseFooButton />
为了清晰起见,我们建议组件的文件名与其名称匹配。因此,在上面的例子中,你可以将 Button.vue 重命名为 BaseFooButton.vue

如果你希望仅基于组件名称而非路径进行自动导入,则需要使用配置对象的扩展形式将 pathPrefix 选项设置为 false

nuxt.config.ts
export default defineNuxtConfig({
  components: [
    {
      path: '~/components',
      pathPrefix: false,    },
  ],
});

这将使用与 Nuxt 2 相同的策略注册组件。例如,~/components/Some/MyComponent.vue 将可用作 <MyComponent> 而不是 <SomeMyComponent>

动态组件

如果你想使用 Vue 的 <component :is="someComputedComponent"> 语法,你需要使用 Vue 提供的 resolveComponent 辅助函数,或者直接从 #components 导入组件并将其传递给 is 属性。

例如:

pages/index.vue
<script setup lang="ts">
import { SomeComponent } from '#components'

const MyButton = resolveComponent('MyButton')
</script>

<template>
  <component :is="clickable ? MyButton : 'div'" />
  <component :is="SomeComponent" />
</template>
如果使用 resolveComponent 处理动态组件,请确保仅插入组件的名称,且必须是字面量字符串,不能是或包含变量。该字符串会在编译时进行静态分析。

或者,虽然不推荐,你可以将所有组件全局注册,这将为所有组件创建异步块,并在整个应用中可用。

  export default defineNuxtConfig({
    components: {
+     global: true,
+     dirs: ['~/components']
    },
  })

你也可以通过将组件放在 ~/components/global 目录中,或在文件名中使用 .global.vue 后缀来选择性地全局注册某些组件。如上所述,每个全局组件都会在单独的块中渲染,因此不要过度使用此功能。

global 选项也可以为每个组件目录单独设置。

动态导入

要动态导入组件(也称为延迟加载组件),只需在组件名称前添加 Lazy 前缀。如果组件并非总是需要,这非常有用。

通过使用 Lazy 前缀,你可以延迟加载组件代码,直到需要时才加载,这有助于优化 JavaScript 包大小。

pages/index.vue
<script setup lang="ts">
const show = ref(false)
</script>

<template>
  <div>
    <h1>山脉</h1>
    <LazyMountainsList v-if="show" />
    <button v-if="!show" @click="show = true">显示列表</button>
  </div>
</template>

延迟(或惰性) hydration

延迟组件非常适合控制应用的块大小,但它们并不总是能提升运行时性能,因为除非有条件渲染,否则它们仍然会急切加载。在现实世界的应用中,有些页面可能包含大量内容和组件,大多数时候并非所有组件都需要在页面加载时立即交互。让它们全部急切加载可能会对性能产生负面影响。

为了优化你的应用,你可能希望延迟某些组件的 hydration,直到它们可见或浏览器完成更重要的任务。

Nuxt 通过延迟(或惰性)hydration 支持这一点,允许你控制组件何时变得可交互。

Hydration 策略

Nuxt 提供了一系列内置的 hydration 策略。每个延迟组件只能使用一种策略。

目前 Nuxt 的内置延迟 hydration 仅适用于单文件组件(SFC),并且要求你在模板中定义 prop(而不是通过 v-bind 展开 prop 对象)。它也不适用于直接从 #components 导入的组件。

hydrate-on-visible

当组件进入视口时进行 hydration。

pages/index.vue
<template>
  <div>
    <LazyMyComponent hydrate-on-visible />
  </div>
</template>
了解更多关于 hydrate-on-visible 的选项。
在底层,这使用了 Vue 内置的 hydrateOnVisible 策略

hydrate-on-idle

当浏览器空闲时进行 hydration。如果需要组件尽快加载但不阻塞关键渲染路径,这很适合。

你还可以传递一个数字作为最大超时时间。

pages/index.vue
<template>
  <div>
    <LazyMyComponent hydrate-on-idle />
  </div>
</template>
在底层,这使用了 Vue 内置的 hydrateOnIdle 策略

hydrate-on-interaction

在指定交互(例如点击、鼠标悬停)后进行 hydration。

pages/index.vue
<template>
  <div>
    <LazyMyComponent hydrate-on-interaction="mouseover" />
  </div>
</template>

如果不传递事件或事件列表,它默认在 pointerenterclickfocus 时进行 hydration。

在底层,这使用了 Vue 内置的 hydrateOnInteraction 策略

hydrate-on-media-query

当窗口匹配媒体查询时进行 hydration。

pages/index.vue
<template>
  <div>
    <LazyMyComponent hydrate-on-media-query="(max-width: 768px)" />
  </div>
</template>
在底层,这使用了 Vue 内置的 hydrateOnMediaQuery 策略

hydrate-after

在指定延迟(以毫秒为单位)后进行 hydration。

pages/index.vue
<template>
  <div>
    <LazyMyComponent :hydrate-after="2000" />
  </div>
</template>

hydrate-when

基于布尔条件进行 hydration。

pages/index.vue
<template>
  <div>
    <LazyMyComponent :hydrate-when="isReady" />
  </div>
</template>
<script setup lang="ts">
const isReady = ref(false)
function myFunction() {
  // 触发自定义 hydration 策略...
  isReady.value = true
}
</script>

hydrate-never

永不 hydration 组件。

pages/index.vue
<template>
  <div>
    <LazyMyComponent hydrate-never />
  </div>
</template>

监听 Hydration 事件

所有延迟 hydration 组件在 hydration 时都会发出一个 @hydrated 事件。

pages/index.vue
<template>
  <div>
    <LazyMyComponent hydrate-on-visible @hydrated="onHydrate" />
  </div>
</template>

<script setup lang="ts">
function onHydrate() {
  console.log("组件已完成 hydration!")
}
</script>

注意事项和最佳实践

延迟 hydration 可以带来性能优势,但必须正确使用:

  1. 优先考虑视口内内容: 避免对关键的、位于页面首屏的内容使用延迟 hydration。它最适合非立即需要的内容。
  2. 条件渲染: 当在延迟组件上使用 v-if="false" 时,你可能不需要延迟 hydration。你可以只使用普通的延迟组件。
  3. 共享状态: 注意多个组件之间的共享状态(v-model)。在一个组件中更新模型可能会触发绑定到该模型的所有组件的 hydration。
  4. 使用每种策略的预期用例: 每种策略都针对特定目的进行了优化。
  • hydrate-when 最适合可能不总是需要 hydration 的组件。
  • hydrate-after 适合可以等待特定时间的组件。
  • hydrate-on-idle 适合在浏览器空闲时进行 hydration 的组件。
  1. 避免对交互组件使用 hydrate-never 如果组件需要用户交互,则不应设置为永不 hydration。

直接导入

如果你想或需要绕过 Nuxt 的自动导入功能,也可以从 #components 显式导入组件。

pages/index.vue
<script setup lang="ts">
import { NuxtLink, LazyMountainsList } from '#components'

const show = ref(false)
</script>

<template>
  <div>
    <h1>山脉</h1>
    <LazyMountainsList v-if="show" />
    <button v-if="!show" @click="show = true">显示列表</button>
    <NuxtLink to="/">首页</NuxtLink>
  </div>
</template>

自定义目录

默认情况下,仅扫描 ~/components 目录。如果你想添加其他目录,或更改在此目录的子文件夹中扫描组件的方式,可以在配置中添加其他目录:

nuxt.config.ts
export default defineNuxtConfig({
  components: [
    // ~/calendar-module/components/event/Update.vue => <EventUpdate />
    { path: '~/calendar-module/components' },

    // ~/user-module/components/account/UserDeleteDialog.vue => <UserDeleteDialog />
    { path: '~/user-module/components', pathPrefix: false },

    // ~/components/special-components/Btn.vue => <SpecialBtn />
    { path: '~/components/special-components', prefix: 'Special' },

    // 如果你希望对 `~/components` 的子目录应用覆盖,必须将此项放在最后。
    //
    // ~/components/Btn.vue => <Btn />
    // ~/components/base/Btn.vue => <BaseBtn />
    '~/components'
  ]
})
任何嵌套目录都需要首先添加,因为它们按顺序扫描。

npm 包

如果你想从 npm 包中自动导入组件,可以在本地模块中使用 addComponent 来注册它们。

import { addComponent, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup() {
    // import { MyComponent as MyAutoImportedComponent } from 'my-npm-package'
    addComponent({
      name: 'MyAutoImportedComponent',
      export: 'MyComponent',
      filePath: 'my-npm-package',
    })
  },
})

组件扩展名

默认情况下,任何在 nuxt.config.tsextensions 键中指定的文件扩展名都会被视为组件。 如果你需要限制应注册为组件的文件扩展名,可以使用组件目录声明的扩展形式及其 extensions 键:

nuxt.config.ts
export default defineNuxtConfig({
  components: [
    {
      path: '~/components',
      extensions: ['.vue'],    }
  ]
})

客户端组件

如果某个组件仅用于客户端渲染,你可以在组件文件名后添加 .client 后缀。

目录结构
| components/
--| Comments.client.vue
pages/example.vue
<template>
  <div>
    <!-- 此组件仅在客户端渲染 -->
    <Comments />
  </div>
</template>
此功能仅适用于 Nuxt 自动导入和 #components 导入。直接从实际路径显式导入这些组件不会将它们转换为仅客户端组件。
.client 组件仅在挂载后渲染。要使用 onMounted() 访问渲染的模板,请在 onMounted() 钩子的回调中添加 await nextTick()
你也可以使用 <ClientOnly> 组件实现类似效果。

服务器组件

服务器组件允许在客户端应用中单独服务器渲染组件。即使你在生成静态站点,也可以在 Nuxt 中使用服务器组件。这使得可以构建混合动态组件、服务器渲染 HTML 甚至静态标记块的复杂站点。

服务器组件可以单独使用,也可以与客户端组件配对使用。

阅读 Daniel Roe 的 Nuxt 服务器组件指南。

独立服务器组件

独立服务器组件将始终在服务器上渲染,也称为 Islands 组件。

当它们的 props 更新时,将触发网络请求,从而原地更新渲染的 HTML。

服务器组件目前是实验性的,要使用它们,你需要在 nuxt.config 中启用“component islands”功能:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    componentIslands: true
  }
})

现在,你可以使用 .server 后缀注册仅服务器组件,并在应用中自动使用它们。

目录结构
-| components/
---| HighlightedMarkdown.server.vue
pages/example.vue
<template>
  <div>
    <!--
      这将自动在服务器上渲染,意味着你的 markdown 解析和代码高亮库
      不会包含在客户端包中。
     -->
    <HighlightedMarkdown markdown="# 标题" />
  </div>
</template>

仅服务器组件在底层使用 <NuxtIsland>,这意味着 lazy 属性和 #fallback 插槽都会传递给它。

服务器组件(和 islands)必须具有单一根元素。(HTML 注释也被视为元素。)
通过 URL 查询参数将 props 传递给服务器组件,因此受 URL 长度限制,注意不要通过 props 传递大量数据给服务器组件。
在 islands 内部嵌套 islands 时要小心,因为每个 island 都会增加一些额外开销。
仅服务器组件和 island 组件的大多数功能(如插槽和客户端组件)仅适用于单文件组件。

服务器组件中的客户端组件

此功能需要配置中的 experimental.componentIslands.selectiveClient 为 true。

你可以通过在希望客户端加载的组件上设置 nuxt-client 属性来部分 hydration 组件。

components/ServerWithClient.vue
<template>
  <div>
    <HighlightedMarkdown markdown="# 标题" />
    <!-- Counter 将在客户端加载和 hydration -->
    <Counter nuxt-client :count="5" />
  </div>
</template>
这仅在服务器组件中有效。客户端组件的插槽仅在 experimental.componentIsland.selectiveClient 设置为 'deep' 时有效,并且由于它们在服务器端渲染,因此在客户端不可交互。

服务器组件上下文

在渲染仅服务器或 island 组件时,<NuxtIsland> 会发起一个 fetch 请求,返回一个 NuxtIslandResponse。(如果在服务器上渲染,这是内部请求;如果在客户端导航渲染,你可以在网络选项卡中看到该请求。)

这意味着:

  • 将在服务器端创建一个新的 Vue 应用来生成 NuxtIslandResponse
  • 在渲染组件时会创建一个新的“island 上下文”。
  • 你无法从应用的其余部分访问“island 上下文”,也无法从 island 组件访问应用的其余上下文。换句话说,服务器组件或 island 与应用的其余部分是_隔离的_。
  • 除非插件设置了 env: { islands: false }(你可以在对象语法插件中设置),否则插件在渲染 island 时会再次运行。

在 island 组件中,你可以通过 nuxtApp.ssrContext.islandContext 访问其 island 上下文。请注意,在 island 组件仍标记为实验性时,此上下文的格式可能会发生变化。

插槽可以是交互式的,并被包裹在带有 display: contents;<div> 中。

与客户端组件配对

在这种情况下,.server + .client 组件是组件的两个“半部分”,可用于在服务器和客户端上实现组件的高级用例。

目录结构
-| components/
---| Comments.client.vue
---| Comments.server.vue
pages/example.vue
<template>
  <div>
    <!-- 此组件将在服务器上渲染 Comments.server,然后在浏览器中挂载后渲染 Comments.client -->
    <Comments />
  </div>
</template>

内置 Nuxt 组件

Nuxt 提供了许多组件,包括 <ClientOnly><DevOnly>。你可以在 API 文档中了解更多信息。

阅读更多 Docs > API.

库作者

使用自动树摇和组件注册创建 Vue 组件库非常简单。✨

你可以使用 @nuxt/kit 提供的 addComponentsDir 方法在 Nuxt 模块中注册你的组件目录。

想象一个这样的目录结构:

目录结构
-| node_modules/
---| awesome-ui/
-----| components/
-------| Alert.vue
-------| Button.vue
-----| nuxt.ts
-| pages/
---| index.vue
-| nuxt.config.ts

然后在 awesome-ui/nuxt.ts 中,你可以使用 addComponentsDir 钩子:

import { createResolver, defineNuxtModule, addComponentsDir } from '@nuxt/kit'

export default defineNuxtModule({
  setup() {
    const resolver = createResolver(import.meta.url)

    // 将 ./components 目录添加到列表
    addComponentsDir({
      path: resolver.resolve('./components'),
      prefix: 'awesome',
    })
  },
})

就是这样!现在在你的项目中,你可以在 nuxt.config 文件中将你的 UI 库作为 Nuxt 模块导入:

nuxt.config.ts
export default defineNuxtConfig({
  modules: ['awesome-ui/nuxt']
})

... 然后在 pages/index.vue 中直接使用模块组件(前缀为 awesome-):

<template>
  <div>
    我的 <AwesomeButton>UI 按钮</AwesomeButton>    <awesome-alert>这是一个警告!</awesome-alert>
  </div>
</template>

它将仅在使用的组件上自动导入,并且在 node_modules/awesome-ui/components/ 中更新组件时支持 HMR。

阅读并编辑实时示例中的内容 Docs > Examples > Features > Auto Imports.