출처: https://joshua1988.github.io/web-development/vuejs/vuex-actions-modules/
(1) Actions란?
Mutations에 비동기처리 로직들이 포함되면 같은 값에 대해 여러 개의 컴포넌트에서 변경을 요청했을 때, 그 변경 순서 파악이 어렵다.
따라서 setTimout() 이나 서버와의 http 통신 처리 같이 결과를 받아올 타이밍이 예측되지 않은 로직은 Actions에 선언한다.
(2) Actions 등록
store.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export const store = new Vuex.Store({
state:{
counter: 0 //counter 라는 state 속성을 추가
},
getters: {
getCounter: function (state) {
return state.counter;
}
},
mutations: {
addCounter: function (state) {
return state.counter++;
},
subCounter: function (state) {
return state.counter--;
},
addDoubleCounter: function (state, payload) {
return state.counter+= payload;
}
},
actions: {
subCounter: function (context) {
return context.commit('subCounter');
//여기의 subCounter는 mutations의 메서드를 의미한다.
}
}
});
상태가 변화하는 걸 추적하기 위헤 actions는 결국 mutaions의 메서드를 호출(commit) 하는 구조가 된다.
(3) Actions 사용
App.vue
<template>
<div id="app">
Parent counter : {{ getCounter }} <br>
<button @click="addCounter">+</button>
<button @click="subCounter">-</button>
<button @click="addDoubleCounter">+2</button>
<child></child> <!--v-bind 삭제-->
</div>
</template>
<script>
import Child from "./Child.vue";
import { mapGetters } from 'vuex'
import { mapMutations } from 'vuex' //mapMutations import
export default {
components: {
// Child 컴포넌트를 하위 컴포넌트로 등록
child: Child
},
data() {
return {
counter: 0
};
},
methods: {
...mapMutations([ //mapMutations 사용
'addCounter'
]),
subCounter(){
this.$store.dispatch('subCounter');
},
addDoubleCounter() {
this.$store.commit('addDoubleCounter',2)
}
},
computed:{
...mapGetters([
'getCounter'
])
}
};
</script>
(4) Acitons에 인자 값 넘기기
(5) mapActions
<template>
<div id="app">
Parent counter : {{ getCounter }} <br>
<button @click="addCounter">+</button>
<button @click="subCounter">-</button>
<button @click="addDoubleCounter">+2</button>
<child></child>
</div>
</template>
<script>
import Child from "./Child.vue";
import { mapGetters } from 'vuex'
import { mapMutations } from 'vuex'
import { mapActions } from 'vuex'//mapActions import
export default {
components: {
child: Child
},
data() {
return {
counter: 0
};
},
methods: {
...mapMutations([
'addCounter'
]),
...mapActions([ //mapActions 사용
'subCounter'
]),
addDoubleCounter() {
this.$store.commit('addDoubleCounter',2);
},
},
computed:{
...mapGetters([
'getCounter'
])
}
};
</script>