//store.js
state:{
num: 10
},
mutations: {
doubleNumber(state){
state.num * 2;
}
},
actions:{
delayDoubleNumber(context) { // context로 store의 메서드와 속성 접근
context.commit('doubleNumber');
}
},
//App.vue
this.$store.dispatch('delayDoubleNumber');
비동기 처리 로직을 선언하는 메소드, 비동기 로직을 담당하는 mutations
데이터 요청, Promise, ES6 async과 같은 비동기 처리는 모두 actions에 선언
예제 1
//store.js
mutations: {
addCounter(state){
state.counter++
}
},
actions:{
delayAddCounter(context){
setTimeout(()=> context.commit('addCounter'),2000);
}
}
// App.vue
methods: {
incrementCounter(){
this.$store.dispatch('delayedAddCounter');
}
}
//store.js
mutations:{
setData(state,fetchedData){
state.product = fetchedData;
}
},
actions: {
fetchProductData(context) {
return axios.get(url)
.then(res => context.commit('setData',response));
// url에 해당하는 response 값을 mutations의 setData를 통해 변경한 뒤 state에 저장
}
}
//App.vue
methods:{
getProduct(){
// actions를 통해 변경된 값을 호출
this.$store.dispatch('fetchProductData');
}
}
출처 : inflearn) Vue.js 중급 강좌 - 장기효