(1) 에 이어서 이번 포스팅에서는 프로젝트에서 사용했던 Flux 패턴에 대해서 소개하고자 한다. 그를 위해 사전지식부터 차근차근 정리하려고 한다.
Vue
나 React
의 경우 무수히 많은 컴포넌트로 구성되어 있다. 데이터를 관리하기 위한 상태관리 패턴인 Vuex
는 React
의 Flux 패턴에서 영향을 받았다고 한다.
MVC 패턴의 복잡한 데이터 흐름의 문제를 해결하는 개발패턴이다.
1. MVC 패턴
위와 같은 형태는 컴포넌트나 기능이 많아지면 아래와 같이 복잡해진다.
그러다보니 기능이 추가됨에 따라 생길 수 있는 문제를 예측할 수가 없다. 또 앱이 커지면서 업데이트가 굉장히 많아질것이다.
2. Flux 패턴
위처렴 Controller를 Action 과 Dispatcher로 분리하여 관리한다.
위 그림을 보고 이해하면 쉽다. 순서는 아래와 같다.
저기서 actions
, mutiotions
, state
는 Vuex라는 Object가 실제로 key값으로 가지고 있으며 getter
를 통해 Vue Components에 전달 할 수 있다. 이 문장은 실제로 vuex를 설치하면 무슨 말인지 단번에 알아 들을 수 있다.
예제는 아래와 같다.
/* store.js */
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
count: 0,
weight: 2,
random: 0,
},
mutations: {
increment(state) {
state.count++;
},
decrement(state) {
state.count--;
},
successGenerateRandomNumber(state, payload){
state.random = payload.num;
},
failGenerateRandomNumber(/*state, payload*/){
console.log('ERROR!');
}
},
getters:{
count(state, getters){
return Math.pow(state.count, getters.weight);
},
weight(state, /*getters*/){
return state.weight;
},
random(state, /*getters*/){
return state.random;
}
},
actions:{
generateRandomNumber({commit, /*state*/}) {
console.log(arguments);
axios.get(`http://localhost:4321/`)
.then((res) => {
commit('successGenerateRandomNumber', res.data);
})
.catch((res) => {
commit('failGenerateRandomNumber', res);
});
}
}
})