LoginSignup
110
107

More than 5 years have passed since last update.

Vue.js + Vuex + async/await で非同期処理

Posted at

まとめ

  • Vue.js + Vuex において非同期処理は、actions 内で実行するのが良い。なぜなら、アクションを定義するメソッドの中で action の dispatch や mutation への commit を任意のタイミングで実行できるので、柔軟に処理を組み合わせることができるからだ。

  • その際、async/await シンタックスで書くことで、非同期処理を「あたかも同期処理のように、上から下へと希望する処理順と同じように書くこと」ができる。これはあくまで見た目であって、非同期処理は非同期処理である。内部的には Promise である。

まずは axios を使った promise ベースの http リクエストをだすメソッドを作る

  • axios は http リクエストをだすためによく使われる npm。
  • async function を作るには、普通の function literal の前に async をつける。
  • async function の中で await を書くと、promise オブジェクトを待ち受けて、それが fulfilled もしくは rejected (ようはなんらかの解決がされる) になるまでそこで停止する。
  • 例えばここでは axios の get が終了するまで await でまつ。取得できたら、res に axios の結果が代入されて、次の行に移動する。
  • async function の中で return した値は promise object として返される。
/api/fetchListAPI.js
import axios from 'axios'

const fetchList = async () => {
  const res = await axios.get("https://api.com/fetch-list", {})
  return res.data
};

export default fetchListAPI

actions の中で dispatch, commit を任意のタイミングでおこなう

  • actions のメソッドは、commit, dispatch を受け取って実行できるので、任意のタイミングで実行すればいい。
  • commit で mutation に、dispatch で action にアクセスできる。
  • actions のメソッドは async function にできるので、その中で await を使うことができる。
  • commit で渡す payload となる引数の場所でも await できる。await dispatch('fetchList')
  • そうした場合、dispatch された action が返す promise オブジェクトを待つことになる。
actions.js
import fetchListAPI from '@/api/fetchListAPI'

const actions = {
  async getList({ commit, dispatch, state }, payload) {
    commit('SET_LIST', await dispatch('fetchList'))
  },
  async fetchList({ commit, dispatch, state }, payload) {
    const list = await fetchListAPI()
    dispatch('dispatchDone')
    return list
  },
  dispatchDone() {
    console.log('fetch done')
  }
}

export default actions

mutations.js
const mutations = {
  SET_LIST(state, payload) {
    console.log('payload', payload)
    state.List = payload
  }
}

export default mutations
110
107
2

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
110
107