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

Nuxtでのサーバー、クライアント間データ共有について

 Nuxtでのサーバー、クライアント間データ共有について

Avatar for Hori Godai

Hori Godai

July 12, 2019
Tweet

More Decks by Hori Godai

Other Decks in Programming

Transcript

  1. serverPrefetch Nuxt 2.6以降から使える! layout やpage コンポーネントで利用可 サーバーサイドでのみ動作するがthis コンテキストも利用できるのが嬉しい! 個人的にはlayoutレベルで必要なデータを取得する際に利用 this.$store.dispatch

    でデータをvuexに送れるのが嬉しい!! Promise をreturn しないとクライアントからは更新されたVuex の結果が見れない! Vue Vue. .extend extend( ({ { serverPrefetch serverPrefetch( () ) { { return return this this. .$store $store. .dispatch dispatch( ('user/fetch' 'user/fetch', , this this. .$ $ } } } }
  2. fetch Nuxt 2.8以降から使える! pageコンポーネントで利用可 this が使えない。。。 個人的にはページレベルで必要なデータを取得する際に利用 Vuex にcommit したりできるぞ!

    Promise をreturn しないとクライアントからは更新されたVuex の結果が見れない! Vue Vue. .extend extend( ({ { async async fetch fetch ( ({ { store store, , params params } }) ) { { const const res res = = await await axios axios. .get get( ('http://my-api/sta 'http://my-api/sta store store. .commit commit( ('setStars' 'setStars', , res res. .data data) ); ; } } } }) )
  3. asyncData あらかじめサーバーサイド側でdata に格納したい値をセットできる! this が使えない。。。。 Vuex にdispatch したりはできなさそう。。。 Vue Vue.

    .extend extend( ({ { asyncData asyncData ( (context context) ) { { return return { { project project: : 'nuxt' 'nuxt' } } } } } }) ); ;
  4. apolloモジュールを使っている場合 @nuxtjs/apollo モジュールを使えばapollo から 取得した値をthis.data に格納できる。 prefetch:true にしておけばサーバーサイドで取得できる! this に依存するコードは書けない

    asyncData に近いイメージ! Vue Vue. .extend extend( ({ { apollo apollo: : { { some some: : { { prefetch prefetch: : true true, , query query: : someGql someGql, , result result( ({ { data data } }) ) { { return return { { some some: : data data. .some some } }; ; } } } } } } } }) ); ;