본문 바로가기

Vue.js

[Vue.js] Vuex이란?

728x90

Vuex는 Vue.js 애플리케이션의 상태 관리 패턴 및 라이브러리입니다. Vuex는 중앙 집중식 저장소(Centralized Store)를 사용하여 모든 컴포넌트 간에 상태를 공유할 수 있게 해줍니다. 이는 대규모 애플리케이션에서 상태 관리가 복잡해질 때 특히 유용합니다. 이번 블로그 글에서는 Vuex의 개념, 구조, 사용법 및 주요 기능에 대해 설명하겠습니다.


Vuex로 상태 관리하기

Vuex는 Vue.js 애플리케이션의 상태 관리를 위해 설계된 라이브러리로, 중앙 집중식 저장소를 통해 컴포넌트 간의 상태 공유를 간편하게 만들어줍니다. Vuex는 단일 상태 트리(Single State Tree)를 사용하여 애플리케이션의 모든 상태를 한 곳에서 관리할 수 있습니다.

Vuex의 주요 개념

  1. State:
    • 애플리케이션의 상태를 저장하는 객체입니다. 컴포넌트는 이 상태를 읽기 전용으로 액세스합니다.
  2. Getters:
    • Vuex의 computed properties와 유사한 역할을 합니다. 상태를 기반으로 계산된 값을 제공합니다.
  3. Mutations:
    • 상태를 변경하는 유일한 방법입니다. 각 뮤테이션은 동기적이어야 하며, commit을 통해 호출됩니다.
  4. Actions:
    • 상태를 변경하는 메서드를 포함합니다. 비동기 작업을 수행할 수 있으며, dispatch를 통해 호출됩니다.
  5. Modules:
    • 상태 관리의 단위입니다. 모듈은 자체 state, mutations, actions, getters를 가질 수 있으며, 애플리케이션을 더 잘 조직할 수 있습니다.

Vuex의 구조

다음은 Vuex의 기본 구조입니다.

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    doubleCount: state => state.count * 2
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment');
      }, 1000);
    }
  },
  modules: {
    // 모듈 정의
  }
});

export default store;

Vuex의 사용법

1. State

상태는 Vuex 스토어의 핵심입니다. 상태는 읽기 전용으로 컴포넌트에서 접근할 수 있으며, this.$store.state를 통해 사용할 수 있습니다.

new Vue({
  el: '#app',
  store,
  computed: {
    count() {
      return this.$store.state.count;
    }
  }
});

2. Getters

게터는 상태를 기반으로 계산된 값을 제공합니다. this.$store.getters를 통해 사용할 수 있습니다.

computed: {
  doubleCount() {
    return this.$store.getters.doubleCount;
  }
}

3. Mutations

뮤테이션은 상태를 변경하는 유일한 방법입니다. commit을 사용하여 뮤테이션을 호출합니다.

methods: {
  increment() {
    this.$store.commit('increment');
  }
}

4. Actions

액션은 비동기 작업을 처리할 수 있습니다. dispatch를 사용하여 액션을 호출합니다.

methods: {
  incrementAsync() {
    this.$store.dispatch('incrementAsync');
  }
}

Modules

Vuex는 모듈을 사용하여 상태 관리를 더 잘 조직할 수 있습니다. 각 모듈은 자체 상태, 뮤테이션, 액션, 게터를 가질 수 있습니다.

const moduleA = {
  state: { count: 0 },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment');
      }, 1000);
    }
  },
  getters: {
    doubleCount(state) {
      return state.count * 2;
    }
  }
};

const store = new Vuex.Store({
  modules: {
    a: moduleA
  }
});

Vuex 사용 예제

다음은 간단한 카운터 애플리케이션 예제입니다.

Vuex 스토어 설정

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment');
      }, 1000);
    }
  },
  getters: {
    count: state => state.count
  }
});

export default store;

Vue 컴포넌트 설정

<template>
  <div id="app">
    <p>{{ count }}</p>
    <button @click="increment">Increment</button>
    <button @click="incrementAsync">Increment Async</button>
  </div>
</template>

<script>
export default {
  computed: {
    count() {
      return this.$store.getters.count;
    }
  },
  methods: {
    increment() {
      this.$store.commit('increment');
    },
    incrementAsync() {
      this.$store.dispatch('incrementAsync');
    }
  }
};
</script>

결론

Vuex는 Vue.js 애플리케이션의 상태 관리를 위한 강력한 도구입니다. 중앙 집중식 저장소를 통해 상태를 관리하면 대규모 애플리케이션의 상태를 효율적으로 관리할 수 있습니다. Vuex의 주요 개념인 state, getters, mutations, actions, modules를 잘 이해하고 활용하면 더욱 유지보수하기 쉽고 확장 가능한 애플리케이션을 개발할 수 있습니다.

'Vue.js' 카테고리의 다른 글

[Vue.js] 라이프사이클(Lifecycle)이란?  (0) 2024.06.10