액션은 변이와 유사하지만
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
액션 핸들러는 저장소 인스턴스의 컨텍스트 객체를 받는다. 그래서, context.commit을 호출해 변이를 커밋하거나 상태, getters에 접근할 수 있다.
액션은 store.dispatch로 시작
store.dispatch('increment')
mutation은 무조건 동기적이어야 하지만 액션은 비동기 작업의 수행이 가능하다
actions: {
incrementAsyn ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
// 페이로드와 함께 디스패치
store.dispatch('incrementAsync', {
amount: 10
})
// 객체와 함께 디스패치
store.dispatch({
type: 'incrementAsync',
amount: 10
})
mapActions를 사용해 컴포넌트에서 액션을 dispatch하거나 컴포넌트 메소드를 store.dispatch호출에 매핑할 수 있다.
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment' // this.increment()를 this.$store.dispatch('increment')에 매핑
]),
...mapActions({
add: 'increment' // this.add()를 this.$store.dispatch('increment')에 매핑
})
}
}
액션 핸들러는 Promise를 반환하므로 체인 형태로 사용이 가능하고 async/await의 사용이 가능하다.