Nuxt/docs/2.guide/2.directory-structure/1.composables.md
Sébastien Chopin f26a801775
docs: update to new website (#23743)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Roe <daniel@roe.dev>
2023-10-18 12:59:43 +02:00

3.0 KiB

title head.title description navigation.icon
composables composables/ Use the composables/ directory to auto-import your Vue composables into your application. i-ph-folder-duotone

Usage

Method 1: Using named export

export const useFoo = () => {
  return useState('foo', () => 'bar')
}

Method 2: Using default export

// It will be available as useFoo() (camelCase of file name without extension)
export default function () {
  return useState('foo', () => 'bar')
}

Usage: You can now use auto imported composable in .js, .ts and .vue files

<script setup lang="ts">
const foo = useFoo()
</script>

<template>
  <div>
    {{ foo }}
  </div>
</template>

:read-more{to="/docs/guide/concepts/auto-imports"}

:link-example{to="/docs/examples/features/auto-imports"}

Types

Under the hood, Nuxt auto generates the file .nuxt/imports.d.ts to declare the types.

Be aware that you have to run nuxi prepare, nuxi dev or nuxi build in order to let Nuxt generate the types.

::callout If you create a composable without having the dev server running, TypeScript will throw an error, such as Cannot find name 'useBar'. ::

Examples

Nested Composables

You can use a composable within another composable using auto imports:

export const useFoo = () => {
  const nuxtApp = useNuxtApp()
  const bar = useBar()
}

Access plugin injections

You can access plugin injections from composables:

export const useHello = () => {
  const nuxtApp = useNuxtApp()
  return nuxtApp.$hello
}

How Files Are Scanned

Nuxt only scans files at the top level of the composables/ directory, e.g.:

| composables/
---| index.ts     // scanned
---| useFoo.ts    // scanned
-----| nested/
-------| utils.ts // not scanned

Only composables/index.ts and composables/useFoo.ts would be searched for imports.

To get auto imports working for nested modules, you could either re-export them (recommended) or configure the scanner to include nested directories:

Example: Re-export the composables you need from the composables/index.ts file:

// Enables auto import for this export
export { utils } from './nested/utils.ts'

Example: Scan nested directories inside the composables/ folder:

export default defineNuxtConfig({
  imports: {
    dirs: [
      // Scan top-level modules
      'composables',
      // ... or scan modules nested one level deep with a specific name and file extension
      'composables/*/index.{ts,js,mjs,mts}',
      // ... or scan all modules within given directory
      'composables/**'
    ]
  }
})