LoginSignup
35
32

More than 3 years have passed since last update.

【Nuxt.js】ページ移動先の、非同期通信のお作法

Last updated at Posted at 2020-10-19

ページ移動先で使うプロパティ

よくページ構築時で使うプロパティとしてmountedがありますが、それだと例えばv-forでコンポーネントを作成する時に、移動した後に構築される動きが見られてしまいます。

そうならないためにも、ページコンポーネントを作成された段階には、v-forで回すデータを格納しておく必要があります。

ここで、登場するのがNuxt.jsだけに許されたasyncDataプロパティというものがあります。

ページコンポーネント構築前の非同期通信と、後の非同期通信の比較

通信タイミング プロパティ 用途 /_idの取得
データ初期化前 async asyncData (context) コンポーネントのdataにデータを格納したい時 context.params.id
データ初期化前 async fetch (context) Vuexのstateにデータを格納したい時 context.params.id
データ初期化以降 async mounted () コンポーネントのdataにデータを格納したい時 this.$route.params.id

mounted等と違うのは、ページロード前にデータを取得できるので、コンポーネントが完成された状態でページを表示することができる

Usage

async asyncData(context) {
  const res = await context.$axios.$get(`/api/offices/${context.params.id}`);
  return {
    office: res,
    office_name: res.name,
    office_introduction: res.introduction,
  };
 },

データ初期化前の処理のため、thisや$メソッドを使うことができない

35
32
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
35
32