#vue - Store

김형우·2022년 3월 18일
0

기술

목록 보기
1/2

Store 사용방법 정리

Store란, vue의 수많은 컴포넌트들이 공통으로 사용 할 변수나 메소드를 등록해 두고 어디서든 꺼내서 가용할 수 있는 창고 역할을 한다.

기본적인 사용은 Store 파일을 생성한 후, 변수를 관리하는 state, 변수를 꺼내쓰는 getters, 외부에서 Store 내부의 state변수를 바꿀 수 있게하는 함수를 설정하는 mutations, 기타 변화를 감지하는 actions로 세팅 한 후 사용한다.

moduleA.js

  1. state에 logged라는 변수를 이용해서 로그인상태인지 아닌지를 판단하려고 한다.
    : 기본값은 logged = false

  2. getters에 getLogged라는 함수를 만들고, 파라미터로 state를 넣는다. 리턴값을 state.logged로 해서 외부에서 getLogged를 꺼내쓰면 그 값이 Store의 state.logged의 값으로 반환되어 표시된다.
    ex) app.vue에서 store의 state를 꺼내쓰는 방법 (여러 모듈일 경우)

const state = reactive({
	logged : computed( () => store.getters['moduleA/getLogged']),
})
  1. mutations에 setLogged라는 함수를 만들고, 파라미터는 state, value 두개를 넣는다. 그러면 외부 컴포넌트에서 commit을 사용해서 setLogged를 호출해 state.logged를 commit에서 명령한 값으로 바꾼다.
    ex) LoginView.vue에서 setLogged를 호출해서 Store의 state.logged를 true로 바꿈, (여러 모듈일 경우)
store.commit('moduleA/setLogged', true);

0. 라이브러리 설치 및 환경설정

  1. store 설치
    : CMD> npm install vuex@next --save

  2. store/index.js 파일 생성
    : 여러개의 store 모듈을 관리하는 역할

  3. store 모듈파일 생성
    : store/module/moduleA.js
    : store/module/moduleB.js

  4. store/index.js에 모듈 등록

  5. main.js에 store/index.js만 등록
    : 모듈은 index.js가 관리하기때문

  6. 사용


1. store/index.js

  1. moduleA와 moduleB를 import한다.
  2. createStore로 모듈들을 외부에서도 사용할수있게 export한다.
import {createStore} from 'vuex';
import { moduleA } from './module/moduleA';
import { moduleB } from './module/moduleB';

export default createStore({
    modules : {moduleA, moduleB}
})

2.

2-1. store/module/moduleA.js

  • 로그인 상태를 저장하는 Store
export const moduleA = {
    
    namespaced : true,

    state : {
        logged : false,
    },
    getters : {
        getLogged(state) {
            return state.logged;
        }
    },
    mutations : {
        setLogged(state, value) {
            state.logged = value;
        }
    },
    actions : {

    }
}

2-2. store/module/moduleB.js

export const moduleB = {
    
    namespaced : true,

    state : {
        num : 10,
    },
    getters : {
        getNum(state) {
            return state.num;
        }
    },
    mutations : {
        setNum(state, value) {
            state.num = value;
        }
    },
    actions : {
        
    }
}
profile
The best

0개의 댓글