mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-11 16:43:55 +00:00
58 lines
2.2 KiB
Markdown
58 lines
2.2 KiB
Markdown
# Auto Imports
|
|
|
|
Nuxt auto-imports helper functions, composables and Vue APIs to use across your application without explicitly importing them. Based on the directory structure, every Nuxt application can also use auto-imports for its own components, composables and plugins. Components, composables or plugins can use these functions.
|
|
|
|
Contrary to a classic global declaration, Nuxt preserves typings and IDEs completions and hints, and only includes what is actually used in your production code.
|
|
|
|
::alert{type=info icon=💡}
|
|
In the documentation, every function that is not explicitly imported is auto-imported by Nuxt and can be used as-is in your code.
|
|
You can find a reference for auto-imported [composables](/api/composables/use-async-data) and [utilities](/api/utils/$fetch) in the API section.
|
|
::
|
|
|
|
::alert{type=warning}
|
|
Auto imports don't currently work within the [server directory](/guide/directory-structure/server).
|
|
::
|
|
|
|
## Nuxt auto-imports
|
|
|
|
Nuxt auto-imports functions and composables to perform [data fetching](/guide/features/data-fetching), get access to the [app context](/api/composables/use-nuxt-app) and [runtime config](/guide/features/runtime-config), manage [state](/guide/features/state-management) or define components and plugins.
|
|
|
|
```vue
|
|
<script setup>
|
|
/* useAsyncData() and $fetch() are auto-imported */
|
|
const { data, refresh, pending } = await useAsyncData('/api/hello', () => $fetch('/api/hello'))
|
|
</script>
|
|
```
|
|
|
|
## Vue auto-imports
|
|
|
|
Vue 3 exposes Reactivity APIs like `ref` or `computed`, as well as lifecycle hooks and helpers that are auto-imported by Nuxt.
|
|
|
|
```vue
|
|
<script setup>
|
|
/* ref() and computed() are auto-imported */
|
|
const count = ref(1)
|
|
const double = computed(() => count.value * 2)
|
|
</script>
|
|
```
|
|
|
|
## Directory-based auto-imports
|
|
|
|
Nuxt directly auto-imports files created in defined directories:
|
|
|
|
- `components/` for [Vue components](/guide/directory-structure/components).
|
|
- `composables/` for [Vue composables](/guide/directory-structure/composables).
|
|
|
|
## Explicit imports
|
|
|
|
Nuxt exposes every auto-import with the `#imports` alias that can be used to make the import explicit if needed:
|
|
|
|
```vue
|
|
<script setup>
|
|
import { ref, computed } from '#imports'
|
|
|
|
const count = ref(1)
|
|
const double = computed(() => count.value * 2)
|
|
</script>
|
|
```
|