5
7

More than 3 years have passed since last update.

nuxt.jsにおけるコンポーネントの規約(没案):ignorePrefixプロパティ版

Last updated at Posted at 2019-04-17
  • 2020/2/4 追記

やはり重い。没案として残しておきます。nuxt.jsにおける「components」ディレクトリの規約(案)をお勧めします。

  • 2019/10/8 追記

ignorePrefixプロパティを使ったファイルが増えると、コンパイル時間が長くなるので注意。

以下本文


nuxt.jsでは、特殊な事情がない限り、3つのディレクトリにコンポーネントが格納される。「layouts」と「pages」と「components」をignorePrefixを活用することで、活かす方法を考えてみる。

コンポーネントの規約(案)

規約はいいすぎか?
以下はシンプルな案なので、みんな仲良く話し合うといい。

今回対象とするコンポーネントファイルとは…

論点がずれないようにコンポーネントファイルについて定義しておく。
今回は「再利用可能」もしくは「複数回利用」するコンポーネントをコンポーネントファイルと呼ぶことにする。

  • 再利用可能なコンポーネント
    • 他プロジェクトでも流用する可能性がある
    • 他プロジェクトでも必ず作成するから置き場を固定したい
  • 複数回利用するコンポーネント
    • UIに関するコンポーネント
    • カテゴリ単位で使い回すコンポーネントなど

※pagesコンポーネントやlayoutコンポーネントは対象から除外。

コンポーネントファイルには、ignorePrefixを必ずつける。

コンポーネントファイルのファイル名の先頭に、-ignorePrefix)を必ずつける。すると、ファイル名にかかわらずなんのファイルか判断することができる。もちろんわかりやすい名前にしたほうが良いのだが…なかなか難しいので。

  • /pages
    • sample.vue ←これはpagesコンポーネントファイル
    • -about.vue ←これはコンポーネントファイル

ディレクトリ構成

Nuxt.js規約の「layouts」「pages」「components」へファイルを振り分ける。呼び出し元のファイルとコンポーネントファイルが近くにあることで探しやすい。

  • /pages
    • index.vue
    • /sample
      • index.vue
      • about.vue
      • -foot-link.vue
      • -side-nav.vue
  • /layout
    • defult.vue
    • -header.vue
    • -nav.vue
    • -footer.vue
  • /components
    • -ui-button.vue
    • -ui-figure.vue
    • -main-section.vue
    • -main-title.vue

以上で規約(案)は終了。ignorePrefixプロパティを活用することで、かなりシンプルに考えられる。

呼び出し方法について

「layouts」と「pages」は、個別にコンポーネントを登録しても手間はない。しかしながら、「components」は肥大化しがちなので一括で登録したい。

個別登録&呼び出し(例)

layouts/default.vue
<template lang="pug">
.layouts
  header.layouts__header
    l-header
    l-nav
  main.layouts__main
    nuxt
  footer.layouts__footer
    l-footer
</template>

<script>
import LHeader from './-header'
import LNav from './-nav'
import LFooter from './-footer'
export default {
  components: {
    LlHeader,
    LNav,
    LFooter,
    ...
  },
  ...
}
</script>

一括登録&呼び出し(例)

plugins経由で登録を行うことで、どこからでも呼び出せるようになるのでcomponents.jsを作成する。

plugins/components.js
import Vue from 'vue'

import UButton from '~/components/-ui-button'
import UFigure from '~/components/-ui-figure'
import MSection from '~/components/-main-section'
import MTitle from '~/components/-main-title'

Vue.mixin({
  components: {
    UButton,
    UFigure,
    MSection,
    MTitle,
  }
})

components.jsをnuxt.confing.jsに登録

nuxt.config.js
module.exports = {
  plugins: [
    { src: '~plugins/components' },
    ...
  ],
}

毎回importしなくても呼び出せるようになる。

test.vue
<template lang="pug">
.main
  m-title(:title="規約大好き" :sub="love")
  m-section
    u-button(to="/") ボタン
</template>

おまけ

ignorePrefixプロパティを使ったファイルが増えると、コンパイル時間が長くなるので注意。こちらの記事をお勧めします。

シンプルに生きたい。

5
7
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
5
7