アクション (actions)
- アクションは、状態を変更するのではなく、ミューテーションをコミットします。
- アクションは任意の非同期処理を含むことができます。
参考:
使い方
参考:
Vue.js で状態管理 Vuex の基本を学ぶ | Cubix
ミューテーションのコミット
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
非同期処理を含むアクション
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
ディスパッチ
アクションは store.dispatch がトリガーとなって実行されます。
increment をディスパッチする(ペイロードなし)
store.dispatch('increment')
ペイロードを使ってディスパッチする
store.dispatch('incrementAsync', {
amount: 10
})
オブジェクトを使ってディスパッチする
store.dispatch({
type: 'incrementAsync',
amount: 10
})
参考:
アクションのディスパッチ – アクション | Vuex [公式]
引数分割束縛
複数回 commit を呼び出す場合に便利
actions: {
increment ({ commit }) {
commit('increment')
}
}
mapActions
参考:
コンポーネント内でのアクションのディスパッチ – アクション | Vuex [公式]
ミューテーションとアクションの違い
参考:
VuexのMutationとActionの切り分け – Qiita
context の型
参考:
What are the types for { dispatch, commit } in vuex? – Stack Overflow