LoginSignup
10
5

More than 3 years have passed since last update.

【Nuxt.js】非同期するなら、$axiosでしょ

Last updated at Posted at 2020-09-21

標準搭載のaxiosと、Nuxtモジュールのaxiosの比較

モジュール axiosの表記
axios axios
@nuxtjs/axios $axios

getと$getの違い

メソッド レスポンス値 実際の値
get レスポンスデータ / ステータスコード / ステータステキスト / ヘッダー / コンフィグ res.data / res.status / res.statusText / res.headers / res.config
$get レスポンスデータ res

セットアップ

$ yarn add @nuxtjs/axios
nuxt.config.js
modules: [
  '@nuxtjs/axios',
],
axios: {
},

Usage getリクエスト

asyncData関数

script
export default {
  async asyncData({ $axios }) {
    const res = await $axios.$get('URL')
    return {
      data: res
    }
  }
}

そのほかでの関数内

script
export default {
  methods: {
    async function () {
      const res = await this.$axios.$get('URL')
      this.data = res
    }
  }
}

Usage postリクエスト

script
export default {
  data () {
    return {
      user: {
        name: '',
        email: '',
        password: '',
      }
    }
  },
  methods: {
    submit: async function () {
      const res = await this.$axios.$post('URL', this.user)
      console.log(res)
    }
  }
}

ルーティング内のid取得に関する比較

関数 /_idの取得
async asyncData (context) context.params.id
その他 this.$route.params.id

番外編:ES6のDestructuring(分割代入)を利用した記述法

関数の引数の省略

script
async asyncData(context) {
  const posts = await context.$axios.$get('/posts')
  return { posts }
},

script
async asyncData ({ $axios }) {
  const posts = await $axios.$get('/posts')
}

関数の引数 & レスポンス値の定数の省略

script
async asyncData (context) {
  const res = await axios.get('/posts/' + context.params.id)
  return { post: res.data }
}

script
async asyncData ({ params }) {
  const { data } = await axios.get('/posts/' + params.id)
  return { post: data }
}
10
5
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
10
5