vuex
의store
뿐만 아니라, 한 파일 내에 담고있는 정보가 너무 많다면, 특정 부분을 별도로 분리해 하나의 파일로 만드는 것이 좋다. 그 때 분리한 하나의 파일을moduel
이라고 하고, 그러한 행위를모듈화
라고 한다.
store.js
import Vue from 'vue';
import Vuex from 'vuex';
import { fetchNewsList, fetchJobsList, fetchAskList } from '../api/index';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
news: [],
jobs: [],
ask: [],
},
getters: {
fetchedAsk(state) {
return state.ask;
},
},
mutations: {
SET_NEWS(state, news) {
state.news = news;
},
SET_JOBS(state, jobs) {
state.jobs = jobs;
},
SET_ASK(state, ask) {
state.ask = ask;
},
},
actions: {
FETCH_NEWS(context) {
fetchNewsList()
.then((response) => {
context.commit('SET_NEWS', response.data);
})
.catch((error) => console.log(error));
},
FETCH_JOBS(context) {
fetchJobsList()
.then(({ data }) => {
context.commit('SET_JOBS', data);
})
.catch((error) => console.log(error));
},
FETCH_ASK(context) {
fetchAskList()
.then(({ data }) => {
context.commit('SET_ASK', data);
})
.catch((error) => console.log(error));
},
},
});
store.js파일 하나에 위보다 몇배가 많은 정보가 쌓이게 된다면, 원하는 정보를 한번에 알아보기 힘들 것이다. 그래서 state
,getters
,mutations
,actions
를 각각 하나의 파일로 만들어준다.
state.js
export default {
news: [],
jobs: [],
ask: [],
}
getters.js
export default {
fetchedAsk(state) {
return state.ask;
}
}
여기에서 신기한 점은, getters.js
파일 내에는 state
라는 값이 없는데 error가 생기지 않는다.
mutations.js
export default {
SET_NEWS(state, news) {
state.news = news;
},
SET_JOBS(state, jobs) {
state.jobs = jobs;
},
SET_ASK(state, ask) {
state.ask = ask;
},
};
actions.js
import { fetchNewsList, fetchJobsList, fetchAskList } from '../api/index';
export default {
FETCH_NEWS(context) {
fetchNewsList()
.then((response) => {
context.commit('SET_NEWS', response.data);
})
.catch((error) => console.log(error));
},
FETCH_JOBS(context) {
fetchJobsList()
.then(({ data }) => {
context.commit('SET_JOBS', data);
})
.catch((error) => console.log(error));
},
FETCH_ASK({commit}) {
fetchAskList()
.then(({ data }) => {
commit('SET_ASK', data);
})
.catch((error) => console.log(error));
},
};
actions
에는 fetchNewsList
와 같이 외부 api를 불러와야 하기 때문에 store.js
에서 import
했던 변수들을 이곳에서 import
해줘야 한다.
그리고 module
과는 관련이 있지는 않지만, FETCH_ASK
를 보면 위의 함수들과는 다르게 들어오는 인자인 commit
을 바로 destructuring
해줘서 아래에서 context.commit
이 아닌 commit
만을 사용할 수도 있다.
store.js
import Vue from 'vue';
import Vuex from 'vuex';
import mutations from './mutations';
import actions from './actions';
Vue.use(Vuex);
export const store = new Vuex.Store({
state,
getters,
mutations,
actions,
});
각각의 내용을 별도의 파일로 분리해줬더니 굉장히 깔끔해졌다.