composables
composables/ ディレクトリを使用して、Vue コンポーザブルをアプリケーションに自動インポートします。
使用方法
方法 1: 名前付きエクスポートを使用する
app/composables/useFoo.ts
export const useFoo = () => {
return useState('foo', () => 'bar')
}
方法 2: デフォルトエクスポートを使用する
app/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')
}
使用方法: 自動インポートされたコンポーザブルは、.js、.ts、および .vue ファイルで使用できるようになりました
app/app.vue
<script setup lang="ts">
const foo = useFoo()
</script>
<template>
<div>
{{ foo }}
</div>
</template>
Nuxt の
app/composables/ ディレクトリは、コードに追加のリアクティビティ機能を提供しません。代わりに、コンポーザブル内のリアクティビティは、ref や reactive などの Vue の Composition API メカニズムを使用して実現されます。リアクティブなコードは、app/composables/ ディレクトリの境界に限定されないことに注意してください。アプリケーションで必要とされる場所であればどこでも、リアクティビティ機能を自由に使用できます。Docs > 4 X > Examples > Features > Auto Imports でライブサンプルを読み、編集する。
タイプ
内部的には、Nuxt は型を宣言するために .nuxt/imports.d.ts ファイルを自動生成します。
Nuxt が型を生成するためには、nuxt prepare、nuxt dev、または nuxt build を実行する必要があることに注意してください。
開発サーバーが実行されていない状態でコンポーザブルを作成すると、TypeScript は
Cannot find name 'useBar'. のようなエラーをスローします。例
ネストされたコンポーザブル
自動インポートを使用して、あるコンポーザブル内で別のコンポーザブルを使用できます
app/composables/test.ts
export const useFoo = () => {
const nuxtApp = useNuxtApp()
const bar = useBar()
}
プラグインの注入にアクセス
コンポーザブルから プラグインの注入 にアクセスできます
app/composables/test.ts
export const useHello = () => {
const nuxtApp = useNuxtApp()
return nuxtApp.$hello
}
ファイルのスキャン方法
Nuxt は、app/composables/ ディレクトリ のトップレベルにあるファイルのみをスキャンします(例:
ディレクトリ構造
-| composables/
---| index.ts // scanned
---| useFoo.ts // scanned
---| nested/
-----| utils.ts // not scanned
インポートのために検索されるのは、app/composables/index.ts と app/composables/useFoo.ts のみです。
ネストされたモジュールで自動インポートを機能させるには、それらを再エクスポートするか(推奨)、またはネストされたディレクトリを含めるようにスキャナーを設定します
例: app/composables/index.ts ファイルから必要なコンポーザブルを再エクスポートします。
app/composables/index.ts
// Enables auto import for this export
export { utils } from './nested/utils.ts'
例: app/composables/ フォルダー内のネストされたディレクトリをスキャンします。
nuxt.config.ts
export default defineNuxtConfig({
imports: {
dirs: [
// Scan top-level composables
'~/composables',
// ... or scan composables nested one level deep with a specific name and file extension
'~/composables/*/index.{ts,js,mjs,mts}',
// ... or scan all composables within given directory
'~/composables/**',
],
},
})