ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Vue.js - Vuex Actions 및 폴더구조화
    IT/Vue.js 2020. 7. 30. 13:31
    반응형

    1. Actions 이란?

     

    Mutations에는 순차적인 로직들만 선언하고 Actions 에는 비 순차적 또는 비동기 처리 로직들을 선언합니다.

    그렇다면 왜 처리 로직의 성격에 따라 Mutations 과 Actions로 나눠 등록해야 할까요?

     

    Mutations의 역할 자체가 State 관리에 주안점을 두고 있습니다. 상태관리 자체가 한 데이터에 대해 여러 개의 컴포넌트가 관여하는 것을 효율적으로 관리하기 위함인데 Mutations에 비동기 처리 로직들이 포함되면 같은 값에 대해 여러 개의 컴포넌트에서 변경을 요청했을 때, 그 변경 순서 파악이 어렵기 때문입니다.

     

    이러한 문제를 방지하기 위해 비동기 처리 로직은 Actions에 동기 처리로직은 Mutations에 나눠 구현합니다.

    따라서, setTimeout() 이나 서버와의 http 통신 처리 같이 결과를 받아올 타이밍이 예측되지 않은 로직은 Actions에 선언합니다.

     


    2. Actions 등록

     

    Vuex에 Actions를 등록하는 방법은 다른 속성과 유사합니다.

    Actions를 선언하고 action method를 추가해줍니다.

     

    // store.js
     
     
    export default new Vuex.Store({
      ....
      mutations: {
        addCounter: function (state, payload) {
          return state.counter++;
        }
      },
      actions: {
        addCounter: function (context) {
          // commit 의 대상인 addCounter 는 mutations 의 메서드를 의미한다.
          return context.commit('addCounter');
        }
      }
    })
    

     

    상태가 변화하는 걸 추적하기 위해 actions 결국 mutations의 메소드를 호출(commit)하는 구조가 된다.

     

     

    // store.js
    export default new Vuex.Store({
      actions: {
        getServerData: function (context) {
          return axios.get("sample.json").then(function() {
            // ...
          });
        },
        delayFewMinutes: function (context) {
          return setTimeout(function () {
            commit('addCounter');
          }, 1000)
        }
      }
    });

     

    위처럼 HTTP get 요청이나 setTimeout과 같은 비동기 처리 로직들은 actions에 선언해줍니다.

     


    3. Actions 사용

     

    앞에서는 mutations를 이용하여 counter를 하나씩 늘렸습니다. 이번엔 actions를 이용해보겠습니다.

    actions를 호출할 때는 아래와 같이 dispatch()를 이용합니다.

     

    // 상위 컴포넌트
     
     
    methods: {
        addCounter () {
            // Mutations를 이용할 때
            // this.$store.commit('addCounter')
     
     
            // Actions를 이용할 때
            this.$store.dispatch('addCounter')
            console.log('Add - state Counter : ' + this.$store.state.counter)
        },
        subCounter () {
            // Mutations를 이용할 때
            // this.$store.commit('subCounter')
     
     
            // Actions를 이용할 때
            this.$store.dispatch('subCounter')
            console.log('Sub - state Counter : ' + this.$store.state.counter)
        }
    }

     

     

     

     

     

    전체 구조도에서 dispatch 의 동작을 보면 아래와 같습니다.

     

     


    4. Actions 결과

     

    Actions이 정상적으로 호출이 되어 Counter의 값이 바뀌는 것을 확인하였습니다.

     

     


    5. 폴더 구조화 & Namespacing

     

    중간 크기 이상의 복잡한 앱을 제작할 때 getters & mutations & actions의 이름을 유일하게 정하지 않으면 namespace 충돌이납니다.

    따라서, 네임스페이스를 구분하기 위해 type.js로 각 속성의 이름들을 빼고 store.js와 각 컴포넌트에 import하며 사용하는 방법이 있습니다.

    혹은, modules라는 폴더를 만들어 각 단위 별로 파일을 쪼개서 관리하는 방법도 있습니다.

     

     

     


    출처 : https://joshua1988.github.io/web-development/vuejs/vuex-actions-modules/

    반응형

    댓글

Designed by black7375.