Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Nuxt.jsのComponent分割単位と,SSRをする上で気をつけること

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.
Avatar for omiend omiend
January 26, 2019

 Nuxt.jsのComponent分割単位と,SSRをする上で気をつけること

Avatar for omiend

omiend

January 26, 2019
Tweet

More Decks by omiend

Other Decks in Programming

Transcript

  1. Nuxtは - Layouts - Pages - Components という単位でページを構成する。 @omiend Nuxt.jsのページ定義

    layouts/default.vue pages/index.vue components/TheFooter.vue components/TheHeader.vue components/SomeSection.vue components/ UserCard.vue components/ TheSideNavi.vue components/ UserCard.vue
  2. @omiend 右ののようなページを作成する場合、下記のようなディレクトリ構 造となる。 . ├── components │ ├── TheSideNavi.vue │

    ├── TheFooter.vue │ ├── TheHeader.vue │ ├── SomeSection.vue │ └── UserCard.vue ├── layouts │ └── default.vue └── pages └── index.vue Nuxt.jsのページ定義 layouts/default.vue pages/index.vue components/TheFooter.vue components/TheHeader.vue components/SomeSection.vue components/ UserCard.vue components/ TheSideNavi.vue components/ UserCard.vue
  3. ざっくりまとめると、弊社では - (HTML5の)Sectionタグ - 部品(Cardなど) の粒度で分割・定義することとした。 Blogに書きました: #Nuxt.jsのComponentをどの単位で分けるか悩んだ話 https://omiend.hatenablog.jp/entry/2018/12/27/203359 @omiend

    layouts/default.vue pages/index.vue components/TheFooter.vue components/TheHeader.vue components/SomeSection.vue components/ UserCard.vue components/ TheSideNavi.vue components/ UserCard.vue Componentsの分割単位
  4. @omiend その上で、書きのディレクトリ構造を少し変更して・・・ . ├── components │ ├── TheSideNavi.vue │ ├──

    TheFooter.vue │ ├── TheHeader.vue │ ├── SomeSection.vue │ └── UserCard.vue ├── layouts │ └── default.vue └── pages └── index.vue Componentsの分割単位 layouts/default.vue pages/index.vue components/TheFooter.vue components/TheHeader.vue components/SomeSection.vue components/ UserCard.vue components/ TheSideNavi.vue components/ UserCard.vue
  5. このような感じにしました。 . ├── components │ ├── parts │ │ └──

    UserCard.vue │ └── sections │ ├── TheSideNavi.vue │ ├── TheFooter.vue │ └── TheHeader.vue ├── layouts │ └── default.vue └── pages └── index.vue @omiend Componentsの分割単位 layouts/default.vue pages/index.vue components/TheFooter.vue components/sections/TheHeader.vue components/sections/ SomeSection.vue components/ parts/ Card.vue components/ sections/ TheSideNavi.vue components/ parts/ Card.vue
  6. TL;DR - Componentsで利用するデータや機能は、 Components内部で完結させたい - Nuxt.jsでSSRをするときは、asyncData()とfetch()を利用する - ComponentsからはasyncData()を利用することが出来ない( Nuxt.jsの仕様) -

    asyncData()はPagesで利用する必要があり、 Componentsにデータを渡す場合は Propsを利用する - Propsは利用したくない - Vuexを利用すれば良い - asyncData()からはVuexのStoreにアクセスできない - fetch()であれば、Storeにアクセスできる まとめ - SSRをしたい - Componentsにデータを渡すか? - Yes - Pagesにfetch()を定義し、Storeにデータを格納 - ComponentsからはStoreのデータを参照する - No - PagesにasyncData()を定義し、Pagesのdata要素とマージさせる @omiend Nuxt.jsにおけるSSRのしかた