Store 사용방법 정리
Store란, vue의 수많은 컴포넌트들이 공통으로 사용 할 변수나 메소드를 등록해 두고 어디서든 꺼내서 가용할 수 있는 창고 역할을 한다.
기본적인 사용은 Store 파일을 생성한 후, 변수를 관리하는 state, 변수를 꺼내쓰는 getters, 외부에서 Store 내부의 state변수를 바꿀 수 있게하는 함수를 설정하는 mutations, 기타 변화를 감지하는 actions로 세팅 한 후 사용한다.
state에 logged라는 변수를 이용해서 로그인상태인지 아닌지를 판단하려고 한다.
: 기본값은 logged = false
getters에 getLogged라는 함수를 만들고, 파라미터로 state를 넣는다. 리턴값을 state.logged로 해서 외부에서 getLogged를 꺼내쓰면 그 값이 Store의 state.logged의 값으로 반환되어 표시된다.
ex) app.vue에서 store의 state를 꺼내쓰는 방법 (여러 모듈일 경우)
const state = reactive({
	logged : computed( () => store.getters['moduleA/getLogged']),
})
store.commit('moduleA/setLogged', true);
store 설치
: CMD> npm install vuex@next --save
store/index.js 파일 생성
: 여러개의 store 모듈을 관리하는 역할
store 모듈파일 생성
: store/module/moduleA.js
: store/module/moduleB.js
store/index.js에 모듈 등록
main.js에 store/index.js만 등록
: 모듈은 index.js가 관리하기때문
사용
import {createStore} from 'vuex';
import { moduleA } from './module/moduleA';
import { moduleB } from './module/moduleB';
export default createStore({
    modules : {moduleA, moduleB}
})
export const moduleA = {
    
    namespaced : true,
    state : {
        logged : false,
    },
    getters : {
        getLogged(state) {
            return state.logged;
        }
    },
    mutations : {
        setLogged(state, value) {
            state.logged = value;
        }
    },
    actions : {
    }
}
export const moduleB = {
    
    namespaced : true,
    state : {
        num : 10,
    },
    getters : {
        getNum(state) {
            return state.num;
        }
    },
    mutations : {
        setNum(state, value) {
            state.num = value;
        }
    },
    actions : {
        
    }
}