0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nuxtでコンポーネントを分割していた際に、コンポーネントが表示されず原因調査に時間を使った。

Nuxtはコンポーネントの自動インポート機能があるのに、どうして表示されないんだろうと原因を探っていたところ、プロジェクトのバージョンによる仕様の違いによるものだった。

前提

今回、以下のような構成でファイルを作成した。

components/
  meo/
    HeroSection.vue
    FeaturesSection.vue
    ...

pages/
  meo/
    index.vue

そして index.vue からコンポーネントを呼び出した。
しかし画面には何も表示されなかった。

原因

package.json を確認したところ、

"nuxt": "^2.15.0"

となっており、今回のプロジェクトはNuxt2だった。

Nuxt 2とNuxt 3/4の違い

Nuxt 3以降ではコンポーネント自動インポートがデフォルトで有効になっている。

components/
  HeroSection.vue

であれば、

<MeoHeroSection />

だけで利用できる。

一方、Nuxt 2ではコンポーネント自動インポートを利用するためには、nuxt.config.jsへ以下のような設定が必要になる。

export default { 
  components: true 
}

この設定が無い場合は、Vueと同じように明示的なimportが必要になる。

<script> 
import HeroSection from '~/components/meo/HeroSection.vue' 
export default { 
 components: { 
   HeroSection
  } 
} 
</script>

対応

毎回コンポーネントごとに import を記述するのは手間だと感じたため、今回は nuxt.config.jscomponents: true を設定し、自動インポートを利用することにした。

学び

「Nuxtだから自動インポートされる」と思い込んでいたが、それは Nuxt 3/4 の知識だった。

まずは利用している Nuxt のバージョンを確認し、そのバージョンの仕様を把握することが大切だと感じた。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?