📦 Vue 상태 관리 - 모듈 분리와 Store 컴포지션 패턴
Vue 상태 관리 시리즈 > 5️⃣ Vuex / Pinia 상태 관리 > 모듈 분리 및 Store 컴포지션 패턴
- 1. 왜 모듈 분리가 필요할까?
- 2. Vuex의 모듈 구조
- 3. namespaced 설정과 네임스페이스 방식
- 4. Pinia에서의 컴포지션 기반 Store 구조
- 5. 실전 구성 팁과 패턴
- 🔚 마무리 & 다음 글 안내
1. 왜 모듈 분리가 필요할까?
애플리케이션 규모가 커질수록 Store 안의 State, Mutation, Action, Getter가 뒤섞여 가독성과 유지보수성이 떨어집니다. 이럴 땐 기능 단위 또는 도메인 단위로 Store를 나누는 “모듈화”가 필요합니다.
2. Vuex의 모듈 구조
기본적으로 Vuex는 하나의 store에 모든 상태를 넣지만, 아래처럼 모듈로 분리할 수 있습니다.
// store/index.js
import { createStore } from 'vuex';
import user from './modules/user';
import product from './modules/product';
export default createStore({
modules: {
user,
product
}
});
// store/modules/user.js
export default {
namespaced: true,
state: () => ({
name: '홍길동'
}),
mutations: {
setName(state, name) {
state.name = name;
}
},
actions: {
updateName({ commit }, name) {
commit('setName', name);
}
},
getters: {
upperName: state => state.name.toUpperCase()
}
};
3. namespaced 옵션이 중요한 이유
namespaced: true
를 설정하면, 모듈 내부의 state나 mutation이 전역과 충돌하지 않고 독립적으로 동작합니다.
- commit 방식:
commit('user/setName')
- getter 접근:
this.$store.getters['user/upperName']
🌟 실전 팁
- namespaced를 안 하면, 서로 다른 모듈에서 mutation 이름이 겹쳐서 디버깅 지옥을 맛보게 됩니다.
- 필요하면
mapState, mapGetters
에namespace
옵션을 사용해 binding하면 됩니다.
4. Pinia에서의 Store 컴포지션 패턴
Pinia는 Store 자체를 함수처럼 정의합니다. 즉, 각 store는 export된 함수이며, 내부에서 state, actions, getters를 정의합니다.
// stores/userStore.js
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
state: () => ({
name: '홍길동'
}),
actions: {
updateName(newName) {
this.name = newName;
}
},
getters: {
upperName: (state) => state.name.toUpperCase()
}
});
// 컴포넌트에서 사용
const userStore = useUserStore();
userStore.updateName('임꺽정');
장점: 모듈을 넘어서 함수 기반으로 분리되기 때문에 훨씬 유연하며, TypeScript와도 찰떡궁합입니다.
5. 실전 구성 팁과 패턴
- Vuex에서는 폴더별로 모듈 구조를 나누고, store/index.js에서 등록하는 구조가 기본입니다.
- Pinia는 store 하나당 파일 하나로 관리하는 것이 가장 직관적입니다.
- 도메인 기준 (user, order, system...)으로 Store를 나누는 것이 유지보수에 유리합니다.
🔚 마무리 & 다음 글 안내
여기까지 Vue 상태 관리를 더 확장성 있게 다루는 모듈 분리 방식과 컴포지션 패턴을 살펴봤습니다.
다음 글에서는 실무에서 자주 사용되는 Axios 인터셉터와 에러 처리 전략에 대해 다룰 예정입니다.
👉 다음 글: Axios 인터셉터 설정과 API 에러 처리
'framework_library > vue' 카테고리의 다른 글
📌 Vue.js에서 전역 EventBus 또는 mitt 활용법 (0) | 2025.05.05 |
---|---|
📌 Axios 인터셉터 설정과 API 에러 처리 (0) | 2025.05.05 |
📦 Vuex에서 Pinia로 마이그레이션 하기 (0) | 2025.05.05 |
📦 Vuex의 구조: State, Mutation, Action, Getter (0) | 2025.05.05 |
📦 상태 관리가 필요한 이유와 Vuex 구조 이해하기 (0) | 2025.05.05 |
댓글