owned mediaウェブ制作に役立つコンテンツを発信中!

Vue.js(Composition API)+TypeScriptの環境でVuex・Vue Router・axiosを使ってみる#4:axiosで非同期通信

最終更新日: Update!!
前回までの記事では、Vuexを使ってアプリの状態管理までを進めてきましたが、今回はaxiosを使って外部のデータを非同期通信で扱ってみたいと思います。一般的なアプリケーション開発でも、バックエンド側からAPIを経由してフロント側でデータを受け取って処理するなどの場面も多々あります。そんな時に便利なのが「axios」でgetやpostなどデータを扱うメソッドが用意されており、JavaScriptに組み込まれているfetch()メソッドなどと比較しても直感的に処理を書くことができます。   これまでの開発環境やコンポーネント、状態管理については過去記事をご参考ください。本記事はこの記事の内容をベースに進めています。 ・Vue.js(Composition API)+TypeScriptの環境でVuex・Vue Router・axiosを使ってみる#1:環境構築 ・Vue.js(Composition API)+TypeScriptの環境でVuex・Vue Router・axiosを使ってみる#2:コンポーネント作成・PropsとEmit ・Vue.js(Composition API)+TypeScriptの環境でVuex・Vue Router・axiosを使ってみる#3:Vuexで状態管理   まずはaxiosのモジュールをインストールしていきます。
$ npm install axios
  axiosが追加されました、これで準備が完了です。
{
  .....
  "dependencies": {
    .....
    "axios": "^0.27.2",
    .....
  },
}
  今回はダミー用のデータを外部のJSONファイルで用意し、そのデータを読み込んでアプリ内で使っていくことにします。実際の開発では静的ファイルではなく、バックエンド側で用意されたAPIに接続する形になります。前回まではデータの中身をコンポーネント側の変数で持たせていたのですが、それをこの外部ファイルに置き換えるような形にします。これを読み込んでコンポーネント内で扱っていきます。 【data.json】
[
  {
    "id": 1,
    "isChecked": false,
    "title": "チェック項目1"
  },
  {
    "id": 2,
    "isChecked": true,
    "title": "チェック項目2"
  },
  {
    "id": 3,
    "isChecked": false,
    "title": "チェック項目3"
  }
]
  続いて、axiosを使った処理を作っていきます。今回はstoreのファイル内でデータを扱うため、mutationsからstateの値に入れる形となりactionsでデータを受け取る処理を書いていきます。TypeScriptの場合ではaxiosで扱う値の型定義を行うので合わせて読み込んでおきます。 【store.ts】
import { InjectionKey } from 'vue';
import { createStore, Store, useStore as baseUseStore } from 'vuex';
import axios, { AxiosResponse, AxiosError } from 'axios';

interface itemInterface {
  id: number,
  isChecked: boolean,
  title: string
}

export interface State {
  draftItems: itemInterface[],
  officialItems: itemInterface[]
  apiData: itemInterface[]
}
export const key: InjectionKey<Store<State>> = Symbol();
export const store = createStore<State>({
  state: {
    draftItems: [],
    officialItems: [],
    apiData: []
  },
  mutations: {
    setDraftItems(state, payload: itemInterface[]) {
      state.draftItems = payload;
    },
    setOfficialItems(state, payload: itemInterface[]) {
      state.officialItems = payload;
    },
    setApiData(state, payload: itemInterface[]) {
      state.apiData = payload;
    }
  },
  actions: {
    updateDraftItems({ commit }, payload: itemInterface[]) {
      commit('setDraftItems', payload);
    },
    updateOfficialItems({ commit }, payload: itemInterface[]) {
      commit('setOfficialItems', payload);
    },
    fatchApiData({ commit }) {
      axios.get('/data.json')
      .then((response: AxiosResponse) => {
        commit('setApiData', response.data);
      })
      .catch((error: AxiosError) => error);
    }
  },
  getters: {
    getDraftItems(state) {
      return state.draftItems;
    },
    getOfficialItems(state) {
      return state.officialItems;
    },
    getApiData(state) {
      return state.apiData;
    }
  }
});
export const useStore = () => {
  return baseUseStore(key);
}
  最後にコンポーネント側から、先ほど作成したaxiosの処理を実行するため、dispatch()メソッドでデータを取得していきます。前回はデータをこのコンポーネント内のデータ変数内で扱っていましたが、stateの値を使う形に変わります。 【app.vue】
<template>
  <section>
    <list-draft :props-items="store.getters.getApiData" />
    <list-official :props-items="store.getters.getOfficialItems" />
  </section>
  <update-button @update-items="update()" />
</template>

<script lang="ts" setup>
  import { reactive, computed } from 'vue';
  import { useStore } from 'vuex';
  import { key } from '../store';
  import ListDraft from './components/ListDraft.vue';
  import ListOfficial from './components/ListOfficial.vue';
  import UpdateButton from './components/UpdateButton.vue';
  interface dataInterface {
    id: number, isChecked: boolean, title: string,
  } 
  const store = useStore(key);
  store.dispatch('fatchApiData');
  const data: { officialItems: dataInterface[] } = reactive({ 
    officialItems: []
  });
  const checkedItems = computed(() => {
    return store.getters.getApiData.filter((item: dataInterface) => {
      return item.isChecked;
    });
  });
  const update = () => {
    data.officialItems = checkedItems.value;
    store.dispatch('updateOfficialItems', data.officialItems);
  }
</script>
  axiosはこのようにgetメソッドでデータを取得する以外にも、postメソッドを使ってデータをバックエンド側に送るなどでもよく使われます。ログインでの認証やデータの登録・更新などで状態管理とセットで覚えておきたいですね。   (こちらの記事も合わせてどうぞ) Vue.js(Composition API)+TypeScriptの環境でVuex・Vue Router・axiosを使ってみる#1:環境構築 Vue.js(Composition API)+TypeScriptの環境でVuex・Vue Router・axiosを使ってみる#2:コンポーネント作成・PropsとEmit Vue.js(Composition API)+TypeScriptの環境でVuex・Vue Router・axiosを使ってみる#3:Vuexで状態管理
  • はてなブックマーク
  • Pocket
  • Linkedin
  • Feedly

この記事を書いた人

Twitter

sponserd

    keyword search

    recent posts

    • Twitter
    • Github
    contact usscroll to top
      • Facebook
      • Twitter
      • Github
      • Instagram