自動探索の有効
v2.13
から、Nuxt はテンプレートで使用されているコンポーネントを自動的にインポートすることができます。この機能を有効にするには、設定ファイルで components: true
を設定してください:
nuxt.config.js
export default {
components: true
}
詳細はhow to configure component auto-discovery を確認してください。
コンポーネントを使う
一度 components ディレクトリにコンポーネントを作成すると、インポートしなくてもアプリ全体で利用できるようになります。
| components/
--| TheHeader.vue
--| TheFooter.vue
layouts/default.vue
<template>
<div>
<TheHeader />
<Nuxt />
<TheFooter />
</div>
</template>
コンポーネントの名前
次ののようなネストされたディレクトリにコンポーネントがある場合:
| components/
--| base/
----| foo/
------| Button.vue
コンポーネント名はそれ自信のパスディレクトリとファイル名をベースにします。したがって、以下のコンポーネントは:
<BaseFooButton />
わかりやすくするために、コンポーネントのファイル名はその名前と一致させることをお勧めします。(つまり、上記の例では、
Button.vue
を BaseFooButton.vue
にリネームすることができます。)コンポーネント名に含まれないカスタムディレクトリ構造を使用したい場合は、これらのディレクトリを明示的に指定することができます:
| components/
--| base/
----| foo/
------| Button.vue
nuxt.config.js
components: {
dirs: [
'~/components',
'~/components/base'
]
}
そして、テンプレートでは、BaseFooButton
の代わりに FooButton
を使用することができます。
pages/index.vue
<FooButton />
コンポーネントやディレクトリの名前は、Vue.js のスタイルガイド を検討してください。
動的インポート
コンポーネントを動的にインポート(コンポーネントの遅延ロードとして知られている)するためには、コンポーネント名に Lazy
という接頭辞を追加するだけです。
layouts/default.vue
<template>
<div>
<TheHeader />
<Nuxt />
<LazyTheFooter />
</div>
</template>
これは、コンポーネントが常に必要なわけではない場合に特に便利です。Lazy
という接頭辞を使えば、コンポーネントのコードの読み込みを適切なタイミングまで遅らせることができるので、JavaScript のバンドルサイズを最適化するのに役立ちます。
pages/index.vue
<template>
<div>
<h1>Mountains</h1>
<LazyMountainsList v-if="show" />
<button v-if="!show" @click="show = true">Show List</button>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
チートシート
このページをGitHubで編集する
更新日 Mon, Aug 19, 2024












































