Vuex

Vuex

Vuex는 컴포넌트 단위로 구성된 Vue Application에서 발생할 수 있는 문제인 전역 데이터 처리를 위한 저장 시스템이다. 애플리케이션이 복잡해지고 컴포넌트가 많아질 수록 상태값, 토큰 등 공유되는 데이터를 효율적으로 관리할 필요성이 생기고, 이 때 vuex 사용이 도움이 된다.

설치

npm

npm install vuex

yarn

yarn add vuex

Vue 연동

Vue application과 연동하기 위해서 다음 코드가 필요하다.

/src/main.js
//vuex 생성 함수 불러오기
import {createStore} from "vuex";
//vuex 저장소 생성
const store = createStore({...});

createApp(App)
            .use(store)//vuex 저장소 사용 설정
            .mount("#app");

JS 분리

저장소 코드가 길어지면 main.js의 가독성이 떨어지므로 분리하여 작성할 수 있다.

다음과 같이 폴더 구조를 작성한다.

src
  +-- main.js
  +-- store
        +-- index.js
src/main.js
import store from "./store";

createApp(/*...*/).use(store).mount(/*...*/);
/src/store/index.js
import {createStore} from "vuex";

const store = createStore({
    /* 중간생략 */
});

export default store;

Vuex 사용

설정이 완료된 경우 Vue Component에서는 this.$store 키워드로 저장소에 접근할 수 있다.

Vuex 구조

vuex의 저장소는 다음과 같은 구조를 가진다.

const store = createStore({
    state: {
    
    }, 
    getters: {
    
    },
    mutations: { 
    
    },
    actions: { 
    
    }
});

각각의 역할은 다음과 같다.

  • state - 저장할 데이터의 원본이 위치하는 영역. 직접 제어를 권장하지 않음.

  • getters - state에 대한 계산 영역. state의 getter 메소드 혹은 computed 메소드를 구현.

  • mutations - state에 대한 변화를 설정하는 영역.

  • actions - mutation을 실행하는 영역. 비동기 작업이 가능.

Last updated