Vue3에서 vuex module분리하는 법
어려운 작업이 아닌데 처음에 할 때 vue3 관련 코드가 없어서 많이 헤맸던 기억이 있다.
1. store폴더 안에 modules폴더를 만든다.
2. 그 안에 모듈 하나씩 파일을 만든다.
예시 : user.ts
import {
SavedMovie, User, Collection, SavedCollection
} from '@/type';
import {
SET_USER,
SET_PASTMOVIE, SET_FUTUREMOVIE,
...
} from '../mutation';
export interface State {
user: User,
pastMovie : SavedMovie[],
futureMovie : SavedMovie[],
collections : Collection[],
savedCollections : SavedCollection[]
}
const user = {
namespaced: true,
state: {
user: {},
pastMovie: [],
futureMovie: [],
collections: [],
savedCollections: []
},
getters: {
isSavedCollection: (state) => (id:number) => {
const result = state.savedCollections.some((p) => p.collectionId === id);
return result;
},
savedId: (state) => (collectionId:number) => {
const result = state.savedCollections.filter((p) => p.collectionId === collectionId);
return result[0].id;
}
},
mutations: {
[SET_USER](state: State, payload:User):void {
state.user = payload;
},
[SET_PASTMOVIE](state: State, payload: SavedMovie[]):void {
state.pastMovie = payload;
},
[SET_FUTUREMOVIE](state: State, payload: SavedMovie[]): void {
state.futureMovie = payload;
},
//생략
},
actions: {
setUser({ commit }, id: number) {
commit('SET_USER', id);
},
setPastMovie({ commit }, movies: SavedMovie[]) {
commit('SET_PASTMOVIE', movies);
},
setFutureMovie({ commit }, movies: SavedMovie[]) {
commit('SET_FUTUREMOVIE', movies);
},
//생략
}
};
export default user;
3. store폴더 안에 index.ts를 만든다.
import Vuex, { createStore } from 'vuex';
import createPersistedState from 'vuex-persistedstate';
import movie from './modules/movie';
import user from './modules/user';
import modal from "./modules/modal";
export default createStore({
modules: {
movie,
user,
modal
},
actions: {
},
plugins: [createPersistedState({
paths: ["user"]
})],
});
module을 등록해준다.
그리고 persistedstate를 쓰고 싶은 모듈은 path에 넣어준다.
4. 파일에서 접근
getters
const allCollectionList = computed(() => store.getters['movie/allCollectionList']);
state
const user = computed(() => store.state.user.user);
dispatch
store.dispatch("modal/openMakeModal", true);
728x90
'WEB > VUE.js' 카테고리의 다른 글
[VUE.js] query string (0) | 2021.12.01 |
---|---|
[VUE.js] vue persistedstate (0) | 2021.12.01 |
[VUE.js] vue-draggable-next로 drag and drop 구현 (0) | 2021.11.30 |
[VUE.js] vue3 selectbox mutiple dropdown구현하기 (0) | 2021.11.27 |
[VUE.js] vue3 intersectionObserver API 를 사용하여 infinite scroll 구현하기 (4) | 2021.11.18 |