Lzh on GitHub

components

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

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

Directory Structure
-| components/
---| AppHeader.vue
---| AppFooter.vue
app.vue
<template>
  <div>
    <AppHeader />
    <NuxtPage />
    <AppFooter />
  </div>
</template>

组件名称

如果您的组件位于嵌套目录中,例如:

Directory Structure
-| 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 prop。

例如:

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 处理动态组件,请确保仅插入组件的名称,该名称必须是文字字符串,并且不能是或包含变量。该字符串在编译步骤中进行静态分析。

或者,虽然不推荐,但您可以全局注册所有组件,这将为所有组件创建异步 chunk,并使它们在整个应用程序中可用。

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

您还可以通过将一些组件放在 ~/components/global 目录中,或在文件名中使用 .global.vue 后缀,来有选择地全局注册它们。如上所述,每个全局组件都在一个单独的 chunk 中渲染,因此请注意不要过度使用此功能。

global 选项也可以按组件目录设置。

动态导入

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

通过使用 Lazy 前缀,您可以延迟加载组件代码,直到合适的时机,这有助于优化您的 JavaScript 包大小。

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

<template>
  <div>
    <h1>Mountains</h1>
    <LazyMountainsList v-if="show" />
    <button v-if="!show" @click="show = true">Show List</button>
  </div>
</template>

延迟(或懒惰)水合

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

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

Nuxt 通过支持延迟(或懒惰)水合来解决这个问题,允许您控制组件何时变得具有交互性。

水合策略

Nuxt 提供了一系列内置的水合策略。每个懒加载组件只能使用一种策略。

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

hydrate-on-visible

当组件在视口中变得可见时进行水合。

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

hydrate-on-idle

当浏览器空闲时进行组件水合。如果您需要组件尽快加载但不阻塞关键渲染路径,则此选项适用。

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

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

hydrate-on-interaction

在指定的交互(例如,点击、鼠标悬停)后水合组件。

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

如果您不传递事件或事件列表,它将默认为在 pointerenterfocus 事件上水合。

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

hydrate-on-media-query

当窗口匹配某个媒体查询时水合组件。

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

hydrate-after

在指定的延迟(以毫秒为单位)后水合组件。

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

hydrate-when

基于布尔条件水合组件。

pages/index.vue
<template>
  <div>
    <LazyMyComponent :hydrate-when="isReady" />
  </div>
</template>
<script setup lang="ts">
const isReady = ref(false)
function myFunction() {
  // trigger custom hydration strategy...
  isReady.value = true
}
</script>

hydrate-never

永远不水合组件。

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

监听水合事件

所有延迟水合的组件在水合时都会触发一个 @hydrated 事件。

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

<script setup lang="ts">
function onHydrate() {
  console.log("Component has been hydrated!")
}
</script>

注意事项和最佳实践

延迟水合可以带来性能优势,但正确使用至关重要:

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

直接导入

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

pages/index.vue

<script setup lang="ts">
  import {NuxtLink, LazyMountainsList} from '#components'

  const show = ref(false)
</script>

<template>
  <div>
    <h1>Mountains</h1>
    <LazyMountainsList v-if="show"/>
    <button v-if="!show" @click="show = true">Show List</button>
    <NuxtLink to="/">Home</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' },

    // It's important that this comes last if you have overrides you wish to apply
    // to sub-directories of `~/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.ts 的 extensions 键 中指定的扩展名的文件都被视为组件。 如果您需要限制应注册为组件的文件扩展名,可以使用组件目录声明的扩展形式及其 extensions 键:

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

客户端组件

如果一个组件仅用于客户端渲染,您可以在组件中添加 .client 后缀。

Directory Structure
| components/
--| Comments.client.vue
pages/example.vue
<template>
  <div>
    <!-- this component will only be rendered on client side -->
    <Comments />
  </div>
</template>
此功能仅适用于 Nuxt 自动导入和 #components 导入。从它们的真实路径显式导入这些组件不会将它们转换为仅客户端组件。

.client 组件仅在挂载后渲染。要使用 onMounted() 访问渲染的模板,请在 onMounted() 钩子的回调中添加 await nextTick()

您还可以使用 <ClientOnly> 组件实现类似的结果。

服务端组件

服务端组件允许在客户端应用程序中服务端渲染单个组件。即使您正在生成静态站点,也可以在 Nuxt 中使用服务端组件。这使得构建复杂的站点成为可能,这些站点混合了动态组件、服务端渲染的 HTML 甚至静态标记块。

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

阅读 Daniel Roe 关于 Nuxt 服务端组件的指南。

独立服务端组件

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

当它们的 props 更新时,这将导致一个网络请求,该请求将就地更新渲染的 HTML。

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

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

现在您可以使用 .server 后缀注册仅服务器端组件,并在应用程序中的任何位置自动使用它们。

Directory Structure
-| components/
---| HighlightedMarkdown.server.vue
pages/example.vue
<template>
  <div>
    <!--
      this will automatically be rendered on the server, meaning your markdown parsing + highlighting
      libraries are not included in your client bundle.
     -->
    <HighlightedMarkdown markdown="# Headline" />
  </div>
</template>

仅服务器端组件在底层使用 <NuxtIsland>,这意味着 lazy prop 和 #fallback slot 都被传递给它。

服务端组件(和岛屿组件)必须具有单个根元素。(HTML 注释也被认为是元素。)
Props 通过 URL 查询参数传递给服务端组件,因此受 URL 可能长度的限制,因此请注意不要通过 props 将大量数据传递给服务端组件。
小心在其他岛屿组件中嵌套岛屿组件,因为每个岛屿组件都会增加一些额外的开销。
大多数仅服务器端组件和岛屿组件的功能(例如 slots 和客户端组件)仅适用于单文件组件。

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

此功能需要在您的配置中将 experimental.componentIslands.selectiveClient 设置为 true

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

components/ServerWithClient.vue
<template>
  <div>
    <HighlightedMarkdown markdown="# Headline" />
    <!-- Counter will be loaded and hydrated client-side -->
    <Counter nuxt-client :count="5" />
  </div>
</template>
这仅在服务端组件内有效。客户端组件的插槽仅在 experimental.componentIsland.selectiveClient 设置为 'deep' 时有效,并且由于它们是在服务端渲染的,因此在客户端不再具有交互性。

服务端组件上下文

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

这意味着:

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

在岛屿组件中,您可以通过 nuxtApp.ssrContext.islandContext 访问其岛屿上下文。请注意,虽然岛屿组件仍被标记为实验性的,但此上下文的格式可能会更改。

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

与客户端组件配对

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

Directory Structure
-| components/
---| Comments.client.vue
---| Comments.server.vue
pages/example.vue
<template>
  <div>
    <!-- this component will render Comments.server on the server then Comments.client once mounted in the browser -->
    <Comments />
  </div>
</template>

内置 Nuxt 组件

Nuxt 提供了许多组件,包括 <ClientOnly><DevOnly>。您可以在 API 文档中阅读更多相关信息。

Read more in Docs > API.

库作者

使用自动 tree-shaking 和组件注册功能创建 Vue 组件库非常简单。✨

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

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

Directory Structure
-| 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)

    // Add ./components dir to the list
    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>
    My <AwesomeButton>UI button</AwesomeButton>!
    <awesome-alert>Here's an alert!</awesome-alert>
  </div>
</template>

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