Vuex로 상태 관리를 편하게 하세요
Vuex란?

Vuex는 모든 구성 요소에서 데이터를 중앙 집중화하는 메커니즘입니다.
Vuex가 없는 환경에서는, 컴퍼넌트간의 데이터의 전달에는, props나 emit에 의한 이벤트를 이용해 실시합니다. 그러나 컴포넌트 간의 데이터 전달이 자주 발생하거나 계층이 늘어나면 porps나 $emit에서의 데이터 관리가 어려워집니다.
이 문제를 해결하는 메커니즘은 Vuex입니다. Vuex라는 하나의 입구에 데이터를 넣으면 어디서나 Vuex의 데이터에 액세스 할 수 있습니다.
Vuex를 설치하여 Vue 앱의 상태 관리를 용이하게 합니다.
먼저 Vuex를 설치합니다.
npm i -S vuex vuex-router-sync
vuex 설치와 함께 "vuex-router-sync"라는 라이브러리도 함께 가져 왔습니다.
이 라이브러리는 Vuex에서 사용하는 store(mutation, getter, actions) 중에서 route 정보를 사용할 수 있도록 하는 라이브러리입니다. Vuex를 사용할 때 편리하기 때문에 함께 넣어두면 좋습니다.
필요한 라이브러리를 가져올 수있는 곳에서 main.js를 다음으로 다시 씁니다.
main.jsimport Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';
import { routes } from './routes';
import store from './store/store';
import { sync } from 'vuex-router-sync'
Vue.use(VueRouter);
const router = new VueRouter({
routes
});
sync(store, router);
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
Vuex에서 상태 관리를 하는 "store/store.js"의 임포트, vuex-router-sync의 임포트, vuex-router-sync를 사용해, router(라우팅)와 store(상태)를 연결하는 처리를 추기.
Vuex에서 상태 관리
Vuex에서 상태 관리를 위해 store라는 디렉토리를 만들고 다음 폴더 구성으로 만들었습니다.
store
├── modules
│ └── counter.js
└── store.js
기본적으로는, modules내에 Vuex로 관리하는 store나 store의 상태를 변경하는 mutations, mutations에 명령을 내는 actions를 쓴 파일을 넣어 갑니다. 그리고 store.js는 이러한 모듈을 함께 main.js로 export합니다.
모든 모듈 파일을 함께 main.js로 내보내는 store.js는 다음과 같습니다.
store.jsimport Vue from 'vue'; /*vueとvuexをインポート*/
import Vuex from 'vuex';
import counter from './modules/counter'; /*vueとvuexをインポート*/
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
counter /*vueとvuexをインポート*/
}
});
다음에 Vuex의 본체가 되는 상태 관리를 담당하는 파일 "modules/counter.js"는 이하와 같은 기술이 되어 있습니다.
counter.jsimport Vue from 'vue'
const state = {
count: 0
};
const mutations = {
'CHANGE_COUNT' (state) {
state.count = state.count + 1;
},
};
const actions = {
plusCount: ({commit}) => {
commit('CHANGE_COUNT');
}
};
const getters = {
currentCount: state => {
return state.count;
}
}
export default {
state,
mutations,
actions,
getters
}
이번에는 방문자를 카운트하는 기능으로 숫자(count)를 Vuex의 state로 관리하고, View측에서 버튼을 누르면 관리하고 있는 숫자가 올라가는 처리를 작성했습니다.
state : 관리하고 싶은 값을 여기에 object 형식으로 기재해 갑니다
mutations:state의 값을 변경하려면 mutations에 명령을 내리고 mutations에서 state의 값을 변경합니다.
actions: View 등으로부터 상태 변경이나 API 통신을 하고 싶을 때, 여기서 정의한 action 을 호출합니다.
getters:state에서 관리하는 값을 참조하고 싶을 때 getters에 액세스합니다. 다양한 형식으로 데이터에 액세스할 수 있도록 합니다.)
이상이 Vuex의 역할입니다.
다음으로 Vuex에서 관리하는 값을 참조하거나 값을 변경하는 버튼이 설치된 파일을 소개합니다.
새로 Counter.vue 파일을 다음과 같이 변경했습니다.
Counter.vue<template>
<div>
<button @click="countUp">add count</button>
<div>{{currentCount}}</div>
</div>
</template>
<script>
export default {
computed: {
currentCount() {
return this.$store.getters.currentCount;
}
},
methods: {
countUp() {
this.$store.dispatch("plusCount");
}
}
}
</script>
이 Vue 컴포넌트를 보면 알 수 있듯이,
버튼을 누르면 "this.$store.dispatch("plusCount");"에서 plusCount 액션에 액세스
this.$store.getters.currentCount에서 Vuex에서 관리하는 store 참조 (getters의 currentCount에 액세스)
컴포넌트에서 플러스 카운트 액션에 "this.$store.dispatch("plusCount");"로 액세스하여 플러스 카운트 액션이 CHANGE_COUNT mutations에 명령을 내리고 상태의 count를 변경합니다.
어쨌든 Vuex의 상태 관리를 알고 있습니다 
마지막으로
Vuex를 사용해, 어느 Component로부터 공통의 state에 액세스 할 수 있게 된 덕분에, Component간에 데이터를 전달해 버리는 비효율적인 어플리케이션 구축으로부터 해방되었군요!
Vuex의 혜택은 대규모 개발이 되면 현저하게 나올 것이라고 생각하기 때문에 배워 두고 손해는 없다고 느꼈습니다.
Reference
이 문제에 관하여(Vuex로 상태 관리를 편하게 하세요), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/yu731994/items/a97a7c8784b2ccec6ff5
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
npm i -S vuex vuex-router-sync
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';
import { routes } from './routes';
import store from './store/store';
import { sync } from 'vuex-router-sync'
Vue.use(VueRouter);
const router = new VueRouter({
routes
});
sync(store, router);
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
store
├── modules
│ └── counter.js
└── store.js
import Vue from 'vue'; /*vueとvuexをインポート*/
import Vuex from 'vuex';
import counter from './modules/counter'; /*vueとvuexをインポート*/
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
counter /*vueとvuexをインポート*/
}
});
import Vue from 'vue'
const state = {
count: 0
};
const mutations = {
'CHANGE_COUNT' (state) {
state.count = state.count + 1;
},
};
const actions = {
plusCount: ({commit}) => {
commit('CHANGE_COUNT');
}
};
const getters = {
currentCount: state => {
return state.count;
}
}
export default {
state,
mutations,
actions,
getters
}
<template>
<div>
<button @click="countUp">add count</button>
<div>{{currentCount}}</div>
</div>
</template>
<script>
export default {
computed: {
currentCount() {
return this.$store.getters.currentCount;
}
},
methods: {
countUp() {
this.$store.dispatch("plusCount");
}
}
}
</script>
Reference
이 문제에 관하여(Vuex로 상태 관리를 편하게 하세요), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/yu731994/items/a97a7c8784b2ccec6ff5텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)