본문 바로가기

Vue/Vue

Vuex4 모듈화, store호출 (2)

Vuex 모듈화

 

단일 상태 트리를 사용하기 때문에 APP의 모든 상태가 객체안에 포함됩니다.
따라서 규모가 커지면 저장소도 비대해 질 수 있습니다. 이를 위해 Vuex는 저장소(store) 를 모듈로 나눌 수 있습니다.

 

// Vue3.0 에서의 store/index
import { createStore } from 'vuex';
import places from "@/store/module/places";
import station from "@/store/module/staion"

export default createStore({
    modules: { places, station }
});

 

파일 구조

 

module/ : 모듈로 나눈 저장소가 위치한 디렉토리 입니다.


index.js : 각 모듈화한 파일들을 가져와 정의하고 내보내는 곳 입니다.

 

 

1. namespaced

위와같이 index.js 에서 모듈화를 하면 store가 복잡해지고 관리하기 힙들어집니다.

 

const station = {
    namespaced: true,
    state: () => ({ ... }),
    mutations: {  ...  },
    getters: {
        getStation: function (state) {
            ...
        }
    },
    actions: {  ...  }
}
export default station;

 

각 모듈의 store에서 namespaced : ture 옵션을 사용하면 member/setInfo 식으로 이름으로 호출이 가능합니다

 

 

Vue3 컴포넌트 에서 store 사용하기

1. getter & mutations

 

...
<script>
import {useStore} from "vuex";

export default {
  name: "Station",
  data() {
    return {
		...
    };
  },
  setup() {
    const store = useStore();
    
    const getData = (() => store.getters('station/getStation'));	//getter
    const setData = ((place) =>  store.commit('station/setSelectStation', place)); //mutations
    
    return {
      getData,
      setData,
    }
  },
 }

 

 

vue2 버전에서와 다르게 vuex에서 제공하는 useStore hook을 사용하여 store에 접근합니다.

(setup()에서 useStore를 정의하여 사용이 가능합니다.)

각각 위와같은 방법으로 getData를 사용하여 getter에 접근해 정보를 가져오고,

setData로 mutations에 접근해 state를 변경하였습니다.

 

2. actions & mutations

//store/module/station.js
...
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment: context => {
      setTimeout(function() {
        context.commit('increment')
      }, 2000)
    }
  }
//component
...
<script>
import {useStore} from "vuex";

export default {
  name: "Station",
  setup() {
    const store = useStore();  
    const increment = () => store.dispatch("station/increment");
    return {
	increment
    }
  },
 }

 

setup() 에서 useStore hook의 dispatch를 사용하여 actions를 실행합니다.

actions 에서는 비동기 함수 setTimeout 사용하여 2초 뒤에 increment mutations 함수를 실행시킵니다

'Vue > Vue' 카테고리의 다른 글

Vuex4에서 state 변경을 감지하는법 (watchEffect)  (0) 2023.04.07
Vuex란? (1)  (0) 2023.04.05
Vue3) Vue-Router  (0) 2023.04.05
Vue.js 3.0 시작하기  (0) 2023.04.05
로그아웃 3 (Springboot + Vue)  (0) 2022.01.25