---
title: "自动导入"
description: "Nuxt 自动导入组件、组合函数、辅助函数和 Vue API。"
canonical_url: "https://nuxt.zhcndoc.com/docs/3.x/guide/concepts/auto-imports"
---
# 自动导入

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

Nuxt 自动导入组件、组合函数和 [Vue.js API](https://vue.zhcndoc.com/api/)，使您无需显式导入便可在整个应用中使用它们。

```vue [app.vue]twoslash
<script setup lang="ts">
const count = ref(1) // ref 是自动导入的
</script>
```

得益于其约定优于配置的目录结构，Nuxt 可以自动导入您的 [`components/`](https://nuxt.zhcndoc.com/docs/3.x/directory-structure/components)、[`composables/`](https://nuxt.zhcndoc.com/docs/3.x/directory-structure/composables) 和 [`utils/`](https://nuxt.zhcndoc.com/docs/3.x/directory-structure/utils)。

与传统的全局声明不同，Nuxt 保留了类型定义、IDE 补全和提示，并且**只包含生产代码中实际使用的内容**。

<note>

在文档中，所有未显式导入的函数都由 Nuxt 自动导入，可以直接在代码中使用。您可以在 [API 部分](https://nuxt.zhcndoc.com/docs/3.x/api)找到自动导入的组件、组合函数和工具函数的参考。

</note>

<note>

在 [`server`](https://nuxt.zhcndoc.com/docs/3.x/directory-structure/server) 目录中，Nuxt 会自动导入 `server/utils/` 中导出的函数和变量。

</note>

<note>

您还可以通过配置 `nuxt.config` 文件中的 [`imports`](https://nuxt.zhcndoc.com/docs/3.x/api/nuxt-config#imports) 部分，自动导入从自定义文件夹或第三方包导出的函数。

</note>

## 内置自动导入

Nuxt 会自动导入用于[数据获取](https://nuxt.zhcndoc.com/docs/3.x/getting-started/data-fetching)、访问[应用上下文](https://nuxt.zhcndoc.com/docs/3.x/api/composables/use-nuxt-app)和[运行时配置](https://nuxt.zhcndoc.com/docs/3.x/guide/going-further/runtime-config)、管理[状态](https://nuxt.zhcndoc.com/docs/3.x/getting-started/state-management)或定义组件和插件的函数和组合函数。

```vuetwoslash
<script setup lang="ts">
/* useFetch() 是自动导入的 */
const { data, refresh, status } = await useFetch('/api/hello')
</script>
```

Vue 提供了诸如 `ref`、`computed` 的响应式 API，以及生命周期钩子和辅助函数，这些都由 Nuxt 自动导入。

```vuetwoslash
<script setup lang="ts">
/* ref() 和 computed() 是自动导入的 */
const count = ref(1)
const double = computed(() => count.value * 2)
</script>
```

### Vue 和 Nuxt 组合函数

在使用 Vue 和 Nuxt 提供的内置 Composition API 组合函数时，请注意许多组合函数要求在正确的_上下文_中调用。

在组件生命周期内，Vue 会通过一个全局变量跟踪当前组件的临时实例（Nuxt 类似地跟踪 `nuxtApp` 的临时实例），随后在同一个事件循环周期内取消这个跟踪。此机制在服务端渲染时尤为重要，用于避免跨请求状态污染（防止两个用户间共享引用泄漏）以及防止组件间状态泄漏。

这意味着（极少数例外），您不能在 Nuxt 插件、Nuxt 路由中间件或 Vue setup 函数之外使用这些组合函数。此外，必须同步使用它们——也就是说，除非在 `<script setup>` 块中、使用 `defineNuxtComponent` 声明的组件的 setup 函数内，或在 `defineNuxtPlugin` 或 `defineNuxtRouteMiddleware` 中，否则不能在调用组合函数前使用 `await`。在这些特殊情况中，Nuxt 会进行转换以保持同步上下文。

如果您遇到类似 `Nuxt instance is unavailable` 的错误提示，通常意味着您在 Vue 或 Nuxt 生命周期中的错误位置调用了 Nuxt 组合函数。

<video-accordion title="观看 Alexander Lichter 讲解如何避免“Nuxt 实例不可用”错误" video-id="ofuKRZLtOdY">



</video-accordion>

<tip>

当在非单文件组件中使用需要 Nuxt 上下文的组合函数时，您需要使用 `defineNuxtComponent` 来包装组件，而非使用 `defineComponent`

</tip>

<read-more to="https://nuxt.zhcndoc.com/docs/3.x/guide/going-further/experimental-features#asynccontext" icon="i-lucide-star">

了解 `asyncContext` 实验性功能，以便在异步函数中使用 Nuxt 组合函数。

</read-more>

<read-more to="https://github.com/nuxt/nuxt/issues/14269#issuecomment-1397352832" target="_blank">

查看该 GitHub 评论中的完整解释。

</read-more>

**错误代码示例：**

```ts [composables/example.ts]twoslash
// 试图在组合函数外部访问运行时配置
const config = useRuntimeConfig()

export const useMyComposable = () => {
  // 这里访问运行时配置
}
```

**正确代码示例：**

```ts [composables/example.ts]twoslash
export const useMyComposable = () => {
  // 因为组合函数在生命周期中的正确位置调用，
  // 所以 useRuntimeConfig 这里可用
  const config = useRuntimeConfig()

  // ...
}
```

## 基于目录的自动导入

Nuxt 会直接自动导入在特定目录中创建的文件：

- `components/` 用于 [Vue 组件](https://nuxt.zhcndoc.com/docs/3.x/directory-structure/components)。
- `composables/` 用于 [Vue 组合函数](https://nuxt.zhcndoc.com/docs/3.x/directory-structure/composables)。
- `utils/` 用于辅助函数和其他工具函数。

<link-example to="https://nuxt.zhcndoc.com/docs/3.x/examples/features/auto-imports">



</link-example>

<warning>

**自动导入的 ref 和 computed 在组件 <template> 中不会被解包。** <br />


这是由于 Vue 对非顶层引用的响应式处理机制导致。您可以在 [Vue 文档](https://vue.zhcndoc.com/guide/essentials/reactivity-fundamentals#caveat-when-unwrapping-in-templates) 中了解更多。

</warning>

### 显式导入

Nuxt 提供 `#imports` 别名，您可以通过它显式导入自动导入的内容，以满足需要时的引用：

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

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

### 禁用自动导入

如果您想禁用组合函数和工具函数的自动导入，可以在 `nuxt.config` 文件中将 `imports.autoImport` 设置为 `false`。

```ts [nuxt.config.ts]twoslash
export default defineNuxtConfig({
  imports: {
    autoImport: false,
  },
})
```

这将完全禁用自动导入，但仍可以从 `#imports` 使用[显式导入](https://nuxt.zhcndoc.com/docs/3.x/guide/concepts/auto-imports#explicit-imports)。

### 部分禁用自动导入

如果您希望框架特定的函数如 `ref` 仍然自动导入，但希望禁用自身代码（例如自定义组合函数）的自动导入，可以在 `nuxt.config.ts` 中将 `imports.scan` 选项设置为 `false`：

```ts
export default defineNuxtConfig({
  imports: {
    scan: false,
  },
})
```

此配置下：

- 框架函数如 `ref`、`computed`、`watch` 等仍可免手动导入使用。
- 自定义代码（如组合函数）则需在文件中手动导入。

<warning>

**注意：** 此设置存在一定限制：

- 若项目采用分层结构，需对各层的组合函数进行显式导入，不能依赖自动导入。
- 这会破坏分层系统的覆盖功能。使用 `imports.scan: false` 前，请充分理解此副作用，并相应调整架构设计。

</warning>

## 自动导入组件

Nuxt 也会自动导入您的 `~/components` 目录下的组件，尽管这项配置独立于组合函数和工具函数的自动导入。

<read-more to="https://nuxt.zhcndoc.com/docs/3.x/directory-structure/components">



</read-more>

若想禁用从您自己的 `~/components` 目录自动导入组件，可以将 `components.dirs` 设置为空数组（但请注意，这不会影响模块增加的组件）。

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

## 来自第三方包的自动导入

Nuxt 还支持从第三方包自动导入。

<tip>

如果您使用了对应包的 Nuxt 模块，模块很可能已经为该包配置了自动导入。

</tip>

例如，您可以这样启用从 `vue-i18n` 包自动导入 `useI18n` 组合函数：

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

<video-accordion title="观看 Alexander Lichter 讲解如何轻松设置自定义自动导入" video-id="FT2LQJ2NvVI">



</video-accordion>


## Sitemap

See the full [sitemap](https://nuxt.zhcndoc.com/sitemap.md) for all pages.
