0
0

More than 3 years have passed since last update.

Vuexで状態管理を行うサンプルコード

Last updated at Posted at 2020-09-04

Vuexを学んだけど実際にどうやって使えば良いのか分からない、という方の参考になれば幸いです。

今回紹介するVuexの流れとしては、

①ActionsでAPIを実行してデータを取得して、Mutationsにcommitする
②MutationsでActionsから受け取った値を、Stateにセットする
③StateにMutationsからセットされた値を格納しておく

です。

index.js
export const state = () => ({
  data: null
})

export const mutations = {
  setData: (state, value) => {
    state.Data = value
  }
}

export const actions = {
  async fetchData({ commit, state }) {
    try {
      const resp = await this.$axios.$get('//ここはAPIを書く//')
      commit('setData', resp)
    } catch (error) {
      console.log(error)
    }
  }
}

ActionsにfetchDataという関数を作成し、
その中でAPIの実行、値をrespに格納しています。
その次の行でcommitを使ってsetDataにrespのデータをコミットしています。

Mutationsではvalueに先ほどコミットしたrespの値が入ってきており、
Stateのdataに値をセットしています。

0
0
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
0
0