ここが変だよ Nuxt.js: No.3 axions の設定、SSR のためのデータのフェッチ
Tweetノーマル axios と違う点
- import axios from 'axios'ではなく、- @nuxt/axiosを- nuxt.config.jsに modules として登録することで、アプリケーションに module として組み込まれる。これを使う。
アプリケーションに登録した axios module を使う
- asyncData のときは ({ $axios }) で受けることができる。
- 通常のコンポーネント、vuex store 内では this.$axios でアクスセスできる。
axios module の使用方法
// Component
// asyncData
async asyncData({ $axios }) { // asyncData という nuxt 特有の機能において
  const ip = await $axios.$get('http://icanhazip.com')
  return { ip }
}
// methods/created/mounted/etc
methods: {
  async fetchSomething() {
    // 通常時は this.$axios でアクセスできる。
    const ip = await this.$axios.$get('http://icanhazip.com')
    this.ip = ip
  }
}
// Store actions (including nuxtServerInit)
// In store
{
  actions: {
    async getIP ({ commit }) {
      // store  内でもアクセスできる
      const ip = await this.$axios.$get('http://icanhazip.com')
      commit('SET_IP', ip)
    }
  }
}asyncData
- コンポーネントが形成されるより前に実行される。
- すなわち SSR に必要な情報を前もって取得するために使う。
- フロント側でもそのページに遷移した際に最初に実行される。
- この中で return したオブジェクトは、既存の vue の data にマージされ使用できる。
asyncData の使用
<template>
  <div>
    <h2>top</h2>
    <div>{{ myName }}</div>
    <button @click="commit">changeName commit mutation</button>
    <button @click="dispatch">changeName dispatch action</button>
    <template v-for="(o, index) in member">
      <div :key="index">{{ o }}</div>
    </template>
  </div>
</template>
<script>
export default {
  computed: {
    myName() {
      return this.$store.state.user.userName
    }
  },
  async asyncData({ $axios }) {
    const url = 'https://api.myjson.com/bins/159wqn'
    const res = await $axios.get(url)
    return res.data // これが data に入る。
  },
  methods: {
    commit() {
      this.$store.commit('user/changeName', 'changedName')
    },
    dispatch() {
      this.$store.dispatch('user/changeName', 'changedName')
    }
  }
}
</script>
<style></style>route.params を利用するために context を利用する
asyncData メソッドは context を引数として受け取る。これには route や params, store などが含まれる。これを活用してデータをフェッチすることができる。
context に含まれる route を活用する
<template>
  <div>
    <h2>test/:id</h2>
    <div>id: {{ id }}</div>
  </div>
</template>
<script>
export default {
  name: 'Index',
  computed: {
    id() {
      return this.$route.params.id
    }
  },
  async asyncData({ $axios, route }) {
    const url = 'https://api.myjson.com/bins/159wqn'
    const res = await $axios.get(url)
    console.log(route.params.id, 'routes')
    return res.data
  }
}
</script>
<style scoped></style>