composables
`composables/` ディレクトリを使用して、Vue composable をアプリケーションに自動インポートします。
使用方法
**方法 1:** 名前付きエクスポートを使用
composables/useFoo.ts
export const useFoo = () => {
return useState('foo', () => 'bar')
}
**方法 2:** デフォルトエクスポートを使用
composables/use-foo.ts または composables/useFoo.ts
// It will be available as useFoo() (camelCase of file name without extension)
export default function () {
return useState('foo', () => 'bar')
}
**使用方法:** 自動インポートされた composable は、.js
、.ts
、.vue
ファイルで使用できます。
app.vue
<script setup lang="ts">
const foo = useFoo()
</script>
<template>
<div>
{{ foo }}
</div>
</template>
Nuxt の
composables/
ディレクトリは、コードに特別なリアクティブ機能を提供しません。 composable 内のリアクティブ性は、ref や reactive など、Vue の Composition API メカニズムを使用して実現されます。 リアクティブコードは、composables/
ディレクトリの境界に限定されません。 アプリケーションの必要な場所でリアクティブ機能を使用できます。ドキュメント > 例 > 機能 > 自動インポート でライブ例を参照および編集できます。
型
内部的には、Nuxt は型を宣言するために .nuxt/imports.d.ts
ファイルを自動生成します。
Nuxt に型を生成させるには、nuxi prepare
、nuxi dev
、または nuxi build
を実行する必要があることに注意してください。
開発サーバーを実行せずに composable を作成すると、TypeScript は
Cannot find name 'useBar'.
などのエラーをスローします。例
ネストされた Composable
自動インポートを使用して、別の composable 内で composable を使用できます。
composables/test.ts
export const useFoo = () => {
const nuxtApp = useNuxtApp()
const bar = useBar()
}
プラグインインジェクションへのアクセス
プラグインインジェクション に composable からアクセスできます。
composables/test.ts
export const useHello = () => {
const nuxtApp = useNuxtApp()
return nuxtApp.$hello
}
ファイルのスキャン方法
Nuxt は、composables/
ディレクトリ の最上位レベルにあるファイルのみをスキャンします。
ディレクトリ構造
-| composables/
---| index.ts // scanned
---| useFoo.ts // scanned
---| nested/
-----| utils.ts // not scanned
composables/index.ts
と composables/useFoo.ts
のみがインポート対象として検索されます。
ネストされたモジュールで自動インポートを機能させるには、再エクスポートするか(推奨)、スキャナーを構成してネストされたディレクトリを含めるかのいずれかになります。
**例:** composables/index.ts
ファイルから必要な composable を再エクスポートします。
composables/index.ts
// Enables auto import for this export
export { utils } from './nested/utils.ts'
**例:** composables/
フォルダー内のネストされたディレクトリをスキャンします。
nuxt.config.ts
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/**'
]
}
})