Usage
Method 1: Using named exportapp/composables/useFoo.ts
app/composables/use-foo.ts
.js, .ts and .vue files
app/app.vue
The
app/composables/ directory in Nuxt does not provide any additional reactivity capabilities to your code. Instead, any reactivity within composables is achieved using Vue’s Composition API mechanisms, such as ref and reactive. Note that reactive code is also not limited to the boundaries of the app/composables/ directory. You are free to employ reactivity features wherever they’re needed in your application.Types
Under the hood, Nuxt auto generates the file.nuxt/imports.d.ts to declare the types.
Be aware that you have to run nuxt prepare, nuxt dev or nuxt build in order to let Nuxt generate the types.
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:app/composables/test.ts
Access plugin injections
You can access plugin injections from composables:app/composables/test.ts
How Files Are Scanned
Nuxt only scans files at the top level of theapp/composables/ directory, e.g.:
app/composables/index.ts and app/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 app/composables/index.ts file:
app/composables/index.ts
app/composables/ folder:
nuxt.config.ts