自动导入

Nuxt 自动导入组件、可组合项、辅助函数和 Vue API。

Nuxt 自动导入组件、可组合项和 Vue.js API,以便在你的应用中使用,而无需显式导入它们。

¥Nuxt auto-imports components, composables and Vue.js APIs to use across your application without explicitly importing them.

app.vue
<script setup lang="ts">
const count = ref(1) // ref is auto-imported
</script>

得益于其自定的目录结构,Nuxt 可以自动导入你的 components/composables/utils/

¥Thanks to its opinionated directory structure, Nuxt can auto-import your components/, composables/ and utils/.

与传统的全局声明相反,Nuxt 会保留输入、IDE 补全和提示,并且仅包含生产代码中使用的内容。

¥Contrary to a classic global declaration, Nuxt preserves typings, IDEs completions and hints, and only includes what is used in your production code.

在文档中,所有未明确导入的函数都会被 Nuxt 自动导入,并且可以在你的代码中按原样使用。你可以在 API section 中找到自动导入组件、可组合项和实用程序的参考。
server 目录中,Nuxt 会自动导入从 server/utils/ 导出的函数和变量。
你还可以通过配置 nuxt.config 文件的 imports 部分,自动导入从自定义文件夹或第三方包导出的函数。

内置自动导入

¥Built-in Auto-imports

Nuxt 自动导入函数和可组合项来执行 数据获取、访问 应用上下文运行时配置、管理 state 或定义组件和插件。

¥Nuxt auto-imports functions and composables to perform data fetching, get access to the app context and runtime config, manage state or define components and plugins.

<script setup lang="ts">
/* useFetch() is auto-imported */
const { data, refresh, status } = await useFetch('/api/hello')
</script>

Vue 公开了类似 refcomputed 的 Reactivity API,以及 Nuxt 自动导入的生命周期钩子和助手。

¥Vue exposes Reactivity APIs like ref or computed, as well as lifecycle hooks and helpers that are auto-imported by Nuxt.

<script setup lang="ts">
/* ref() and computed() are auto-imported */
const count = ref(1)
const double = computed(() => count.value * 2)
</script>

Vue 和 Nuxt 可组合项

¥Vue and Nuxt Composables

当你使用 Vue 和 Nuxt 提供的内置 Composition API 可组合组件时,请注意其中许多组件依赖于在正确的上下文中调用。

¥When you are using the built-in Composition API composables provided by Vue and Nuxt, be aware that many of them rely on being called in the right context.

在组件生命周期中,Vue 通过全局变量跟踪当前组件的临时实例(类似地,Nuxt 跟踪 nuxtApp 的临时实例),然后在同一 tick 中取消设置。这在服务器渲染时至关重要,既可以避免跨请求状态污染(在两个用户之间泄漏共享引用),也可以避免不同组件之间的泄漏。

¥During a component lifecycle, Vue tracks the temporary instance of the current component (and similarly, Nuxt tracks a temporary instance of nuxtApp) via a global variable, and then unsets it in same tick. This is essential when server rendering, both to avoid cross-request state pollution (leaking a shared reference between two users) and to avoid leakage between different components.

这意味着(除了极少数例外),你不能在 Nuxt 插件、Nuxt 路由中间件或 Vue 设置函数之外使用它们。此外,你必须同步使用它们。 - 也就是说,你不能在调用可组合项之前使用 await,除非在 <script setup> 块中、在用 defineNuxtComponent 声明的组件的 setup 函数中、在 defineNuxtPlugindefineNuxtRouteMiddleware 中,在这些情况下,我们会执行转换以保持同步上下文,即使在 await 之后也是如此。

¥That means that (with very few exceptions) you cannot use them outside a Nuxt plugin, Nuxt route middleware or Vue setup function. On top of that, you must use them synchronously - that is, you cannot use await before calling a composable, except within <script setup> blocks, within the setup function of a component declared with defineNuxtComponent, in defineNuxtPlugin or in defineNuxtRouteMiddleware, where we perform a transform to keep the synchronous context even after the await.

如果你收到类似 Nuxt instance is unavailable 的错误消息,则可能意味着你在 Vue 或 Nuxt 生命周期中的错误位置调用了 Nuxt 可组合项。

¥If you get an error message like Nuxt instance is unavailable then it probably means you are calling a Nuxt composable in the wrong place in the Vue or Nuxt lifecycle.

在非 SFC 组件中使用需要 Nuxt 上下文的可组合项时,需要使用 defineNuxtComponent 而不是 defineComponent 封装组件。

:

Read more in Docs > Guide > Going Further > Experimental Features#asynccontext.

查看 asyncContext 实验性功能,了解如何在异步函数中使用 Nuxt 可组合项。

¥Checkout the asyncContext experimental feature to use Nuxt composables in async functions.

::

:

Read more in https://github.com/nuxt/nuxt/issues/14269#issuecomment-1397352832.

请参阅此 GitHub 评论中的完整解释。

¥See the full explanation in this GitHub comment.

::

代码执行失败示例:

¥Example of breaking code:

composables/example.ts
// trying to access runtime config outside a composable
const config = useRuntimeConfig()

export const useMyComposable = () => {
  // accessing runtime config here
}

代码运行示例:

¥Example of working code:

composables/example.ts
export const useMyComposable = () => {
  // Because your composable is called in the right place in the lifecycle,
  // useRuntimeConfig will work here
  const config = useRuntimeConfig()

  // ...
}

基于目录的自动导入

¥Directory-based Auto-imports

Nuxt 直接自动导入在指定目录中创建的文件:

¥Nuxt directly auto-imports files created in defined directories:

Read and edit a live example in Docs > Examples > Features > Auto Imports.
自动导入的 refcomputed 不会被解包到 <template> 组件中。:br 这是由于 Vue 处理非模板顶层引用的方式所致。你可以在 在 Vue 文档中 上阅读更多相关信息。¥Auto-imported ref and computed won't be unwrapped in a component <template>.
This is due to how Vue works with refs that aren't top-level to the template. You can read more about it in the Vue documentation.

显式导入

¥Explicit Imports

Nuxt 使用 #imports 别名公开每个自动导入,如果需要,可以使用该别名显式导入:

¥Nuxt exposes every auto-import with the #imports alias that can be used to make the import explicit if needed:

<script setup lang="ts">
import { ref, computed } from '#imports'

const count = ref(1)
const double = computed(() => count.value * 2)
</script>

禁用自动导入

¥Disabling Auto-imports

如果你想禁用自动导入可组合项和实用工具,可以在 nuxt.config 文件中将 imports.autoImport 设置为 false

¥If you want to disable auto-importing composables and utilities, you can set imports.autoImport to false in the nuxt.config file.

nuxt.config.ts
export default defineNuxtConfig({
  imports: {
    autoImport: false
  }
})

这将完全禁用自动导入,但仍然可以使用 #imports 中的 显式导入

¥This will disable auto-imports completely but it's still possible to use explicit imports from #imports.

部分禁用自动导入

¥Partially Disabling Auto-imports

如果你希望特定于框架的函数(例如 ref)保持自动导入,但希望禁用你自己的代码(例如,自定义可组合函数)的自动导入,则可以在 nuxt.config.ts 文件中将 imports.scan 选项设置为 false

¥If you want framework-specific functions like ref to remain auto-imported but wish to disable auto-imports for your own code (e.g., custom composables), you can set the imports.scan option to false in your nuxt.config.ts file:

export default defineNuxtConfig({
  imports: {
    scan: false
  }
})

使用此配置:

¥With this configuration:

  • 从小型项目到大型 Web 应用,Vue 都能在规模化环境中保持良好的性能,确保你的应用持续为用户提供价值。
  • 自定义代码(例如可组合项)需要手动导入到你的文件中。
注意:此设置有一定的限制:¥Caution: This setup has certain limitations:
  • 如果你使用层级结构构建项目,则需要明确导入每个层级中的可组合项,而不是依赖自动导入。
  • 这会破坏层系统的覆盖功能。如果你使用 imports.scan: false,请确保你了解此副作用并相应地调整你的架构。

自动导入的组件

¥Auto-imported Components

Nuxt 还会自动从你的 ~/components 目录导入组件,尽管这与自动导入可组合项和实用程序函数的配置是分开的。

¥Nuxt also automatically imports components from your ~/components directory, although this is configured separately from auto-importing composables and utility functions.

Read more in Docs > Guide > Directory Structure > Components.

要禁用从你自己的 ~/components 目录自动导入组件的功能,你可以将 components.dirs 设置为空数组(但请注意,这不会影响模块添加的组件)。

¥To disable auto-importing components from your own ~/components directory, you can set components.dirs to an empty array (though note that this will not affect components added by modules).

nuxt.config.ts
export default defineNuxtConfig({
  components: {
    dirs: []
  }
})

从第三方包自动导入

¥Auto-import from Third-Party Packages

Nuxt 还允许从第三方包自动导入。

¥Nuxt also allows auto-importing from third-party packages.

如果你正在为该包使用 Nuxt 模块,则该模块很可能已经为该包配置了自动导入。

例如,你可以像这样启用从 vue-i18n 包自动导入 useI18n 可组合项的功能:

¥For example, you could enable the auto-import of the useI18n composable from the vue-i18n package like this:

nuxt.config.ts
export default defineNuxtConfig({
  imports: {
    presets: [
      {
        from: 'vue-i18n',
        imports: ['useI18n']
      }
    ]
  }
})