이안의 평일코딩

[Vue] Vuex(3) - actions, $store.dispatch(), context 본문

Front-end/Vue

[Vue] Vuex(3) - actions, $store.dispatch(), context

이안92 2021. 5. 18. 18:45
반응형

 actions

 

ajax요청과 같이 시간이 오래걸리는 것을 처리하기 위해서는 actions을 이용한다.

비동기식 처리를 지원하는 코드는 다음줄 부터 실행하려는 경향이 있기 때문에

의도치않는 버그가 생길 수 있고, 코드가 길어져 복잡해질 수 있다.

그래서 mutations: {}가 아닌 ajax 요청하지 않고 actions: {}에서 한다.

 

더보기 게시물 ajax를 요청해보자.

 

store.js
import axios from 'axios';
import { createStore } from 'vuex'

const store = createStore({
    state () {
        return {
            more : {},
        }
    },
    actions : {
        getData(){
            axios.get('URL.json')
            .then((a)=>{
                console.log(a.data) // ajax로 받아온 데이터
            })
        },
    },
})

export default store;

getData()라는 함수를 actions에서 정의해준다.

 

App.vue
<template>
  <p>{{ $store.state.more }}</p>
  <button @click="$store.dispatch('getData')">더보기</button>
</template>

$store.dispatch()actions에 부탁하는 것이고, $store.commitmutations에 부탁한다.

 


App.vue에서 더보기 버튼으로 데이터를 가져온 뒤 (actions 후)

state를 변경하려면 무조건 mutations에서 한다.

store.js
import axios from 'axios';
import { createStore } from 'vuex'

const store = createStore({
    state () {
        return {
            more : {},
        }
    },
    mutations :{
        setMore(state, data){
            state.more = data
        },
    },
    actions : {
        getData(context){
            axios.get('URL.json')
            .then((a)=>{
                console.log(a.data) // ajax로 받아온 데이터
                context.commit('setMore', a.data)
            })
        },
    },
})

export default store;

dispatch로 가져온 데이터를 setMore()라는 함수를 이용해 more이라는 state에 데이터를 넣어준다.

actions안에 mutations에 부탁하기 위한 commit()을 사용하려면 context를 이용한다.

 

정리하자면, 더보기 버튼을 누르면 dispatch('getData')로 ajax를 통해 데이터를 가져오는데

가져온 데이터를 저장하기 위해 mutations 함수를 이용해서 state에 저장한다.

반응형
Comments