TIL - Vuex 모듈화

Taesol Kwon·2020년 10월 19일
0

Vuex 모듈화에 대해 이전에 공부를 했었지만 실제로 업무에 적용한 건 이번이 처음이였다.

작업을 하면서도 적용할까...말까..를 반복하던 찰나에 store가 비대해짐을 느끼고 모듈화 시키기로 결정했다.

//index.js
import Vue from "vue";
import Vuex from "vuex";

import actorStore from "./modules/actorStore";
import adminStore from "./modules/adminStore";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    accessToken: null, // rootState 가 된다.
  },
  getters: { // rootGetters가 된다.
    TOKEN(state) { 
      return state.accessToken === null
        ? localStorage.accessToken
        : state.accessToken;
    },
  },
  mutations: {
    SET_TOKEN(state, { token, role }) {
      state.accessToken = token;

      localStorage.accessToken = token;
    },
    REMOVE_TOKEN(state) {
      state.accessToken = null;

      localStorage.removeItem("accessToken");
    },
  },
  modules: {
    actorStore: actorStore,
    adminStore: adminStore,
  },
});

export default store;
// adminStore.js
const adminStore = {
  namespaced: true,
  state: {
    userList: null,
  },
  getters: {
    USER_LIST(state) {
      return state.userList;
    },
  },
  mutations: {
    // Admin용 유저 리스트
    SET_USERLIST(state, fetchedData) {
      state.userList = fetchedData;
    },
  },
  actions: {
    // 유저 리스트 가져오는 API
    async FETCH_GET_USERLIST({ state, commit, rootGetters }) {
      const options = {
        method: "POST",
        headers: {
          Authorization: `Bearer ${rootGetters.TOKEN}`, //localStore에서는 
        },
      };
      const res = await fetch(`/v1/for-admin/actors/list`, options);
      const data = await res.json();
      if (!state.userList) commit("SET_USERLIST", await data.data.Value);
      commit("SET_USERLIST", data.data.Value);
    },
  },
};

export default adminStore;

필자는 이와같이 모듈화를 진행하였다.

📍주의할점
LocalStore에서는 scope가 해당 local이기 때문에 다른 localStore에 접근할 수 없고, 오직 globalStore(index.js)에만 접근 할 수 있다. 설명은 공식홈페이지 에 잘 나와있다.

vue 템플릿에서 vuex 스토어에 접근하는 방법은 아래와 같다.

// admin.vue
<template>
</template>

<script>
import { mapGetters, mapActions, mapMutations } from "vuex";

const adminStore = "adminStore";

export default {
  computed: {
  ...mapGetters(["TOKEN"]),
  ...mapGetters(adminStore, ["USER_LIST"])
  // or 
  ...mapGetters(adminStore, {userList: "USER_LIST"}) 
  }
}
</script>

이와 같이 접근해주면 된다~!! 너무 쉽다:)

profile
사진촬영을 좋아하는 프론트엔드 개발자입니다.

0개의 댓글