【Nuxt.js】axiosのインストール方法と使い方を、プロジェクトの作成から解説

Nuxt.js

Nuxt.jsにaxiosを導入する方法とその使い方を、プロジェクトを作成するところから解説します。

こんにちは、aiiro(@aiiro29)です。

この記事は、次のような方に向けた内容となっています。

「nuxt-community/axios-moduleがあるらしいけれど、npmを使ってaxiosをインストールする以外に何か設定しないといけないらしい」
「axios-moduleをインストールするところまではできたけれど、どうやってaxiosを呼び出せばいいかがわからない」

スポンサーリンク

プロジェクトの作成

vue init を使用してサンプルのプロジェクトを作成します。


vue init nuxt-community/starter-template nuxt-with-axios

つぎに、npmをインストールして開発環境が起動できるかどうか確認します。


npm install

npm run dev

この画面が表示されていれば、起動はOKです。

axiosの導入

nuxt-communityが提供しているaxiosモジュールを使用します。

GitHub - nuxt-community/axios-module: Secure and easy axios integration with Nuxt.js
Secure and easy axios integration with Nuxt.js. Contribute to nuxt-community/axios-module development by creating an account on GitHub.

axiosモジュールをインストール

まずは npm install でaxiosをインストールします。


npm install --save @nuxtjs/axios

nuxt.config.jsの設定

コンポーネントでaxiosを使用する前に、 nuxt.config.js を設定する必要があります。

下記を参考にして、modulesaxios を追加してください。

module.exports = {
  /*
  ** Headers of the page
  */
  head: {
    title: 'nuxt-with-axios',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Nuxt.js project' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  // 中略

  modules: [
    '@nuxtjs/axios',
  ],
  axios: {
  }
}

ページコンポーネントでaxiosを利用する

設定ができたところで、axiosを使ってリクエストの送信ができるかどうか試します。

pages/index.vue のページコンポーネントを下記の内容に書き換えます。

asyncData()でaxiosを呼び出す

<template>
  <div>
    {{ host }}
  </div>
</template>

<script>
export default {
  components: {
  },
  data() {
    return {
        host: ''
    };
  },
  async asyncData({ app }) {
    const response = await app.$axios.$get('https://httpbin.org/get');
    return { host: response.headers.Host };
  }
}
</script>

Nuxt.jsを起動すると、ブラウザに https://httpbin.org/get から取得したホスト名(httpbin.org)が表示されます。

注意点

上記では、URLを開いたときにデータを表示するために、asyncData()を使用しました。


覚えておきたいのは、asyncData()はページコンポーネント以外のコンポーネントでは動作しないことです。
なぜかというと、コンポーネントのロードより前にasyncData()がロードされるのは、ページコンポーネントの場合だけだからです。

Data Fetching
In Nuxt we have 2 ways of getting data from an API. We can use the fetch method or the asyncData method.
The context
The context provides additional objects/params from Nuxt to Vue components and is available in special nuxt lifecycle areas.

最初はcomponents配下にコンポーネントを作成して、asyncData()を追加したのですが、動かなくてハマりました。。

ページコンポーネント以外のコンポーネントで非同期なデータを扱うには、下記のドキュメントを参照してください。

Data Fetching
In Nuxt we have 2 ways of getting data from an API. We can use the fetch method or the asyncData method.

methods()でaxiosを呼び出す

今度はメソッド内でaxiosを使用する方法を確認します。

pages/index.vue を次のように書き換えます。

<template>
  <div>
    <p>{{ host }}</p>
    <button @click="sendRequest">リクエスト</button>
    <p>{{ accept }}</p>
  </div>
</template>

<script>
export default {
  components: {
  },
  data() {
    return {
        host: '',
        accept: ''
    };
  },
  methods: {
    async sendRequest() {
      const response = await this.$axios.$get('https://httpbin.org/get');
      this.accept = response.headers.Accept;
    }
  },
  async asyncData({ app }) {
    const response = await app.$axios.$get('https://httpbin.org/get');
    return { host: response.headers.Host };
  }
}
</script>

リクエストボタンを押すと、sendRequest()を実行して、リクエストを送信します。
レスポンスの取得に成功すると、リクエストボタンの下に結果が表示されます。

ポイント

メソッド内部でaxiosを呼び出すときは、asyncData()の場合と違い、 this.$axios としている点にご注意ください。

参考

Usage