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に値をセットしています。