앞에서 우리는 state, getters, mutations 에 대해 배워보았습니다.
이번엔 Actions에 대해 다뤄보겠습니다.
따라서, setTimeout()
이나 서버와의 http 통신 처리 같이 결과를 받아올 타이밍이 예측되지 않는 비동기적인 로직은 Actions 에 선언합니다.
mutations:{
doubleCounter: function(state,payload){
return state = state*payload;
}
},
actions:{
addCounter: function (context) {
// commit 의 대상인 doubleCounter 는 mutations 의 메서드를 의미한다.
return context.commit('doubleCounter');
}
}
state 값을 추적하기 위해 결과적으론 actions 에서 mutations 을 호출하는 ( commit ) 구조가 됩니다.
이 actions 의 핸들러는 context
객체를 인자로 전달받는데, 이 context
는 store 의 메소드와 속성을 가지고 있는 객체입니다.
래서 context.commit
를 호출하여 Mutation의 핸들러를 호출하거나, context.state
와 context.getters
를 통해 state와 getter에 접근 할 수 있습니다.
그러나 보통 context.commit
만 사용하기 때문에 코드 단순화를 위해 구조분해할당을 사용할 수 있습니다. 바로 이렇게 말이죠.
actions: { increment ({ commit }) { commit('increment') } }
컴포넌트에서 actions 을 호출하기 위해서는 store.dispatch
를 사용합니다.
// Parent.vue
methods: {
// Mutations 를 이용할 때
addCounter() {
this.$store.commit('addCounter');
}
// Actions 를 이용할 때
addCounter() {
this.$store.dispatch('addCounter');
}
},
actions 역시 mutations 처럼 인자를 넘겨줄 수도 있다.