Vue는 기본적으로 하나의 component에 대해서 지역 state(data)가 전부 존재하고, 부모 컴포넌트와 자식 컴포넌트가 props, event를 이용한 noti를 통해 state를 공유할 수 있도록 한다.
또한 Vue를 이용한 global event bus를 이용하여 부모 자식 간이 아니어도 서로 통신할 수 있는 방법이 있다. https://kr.vuejs.org/v2/guide/components.html#비-부모-자식간-통신
하지만 여러개의 컴포넌트 사이에서 더 복잡한 방식으로 state가 공유되서 관리되어야 하는 경우, Vuex를 통해서 외부의 상태 관리를 원활하게 할 수 있도록 한다.
Vuex는 공통의 상태를 공유하는 여러 컴포넌트를 위한 전역 상태 관리 라이브러리이다.
state: 전역으로 관리되는 data
mutations: state를 변경시켜주는 함수들의 집합. 항상 mutation을 통해서 state를 변경시켜주어야 함.
store.commit({{mutation이름}}) 함수를 통해서 mutation을 실행시킴 → store.state.count로 state에 접근이 가능 component에서는 해당 store을 이용해 computed 속성을 정의하면 된다. component에 store을 정의하면 Vuex의 store을 사용할 수 있고, this.$store을 이용해 접근할 수 있다.
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
});
store.commit('increment'); // commit method,
console.log(store.state.count); //
new Vue({
el: '#app',
store,
data: {
message: 'Hello world'
}
computed: {
count () {
return this.$store.state.count
}
}
});
여러 상태 속성을 사용해야하는 경우 mapState를 이용해서 간결하게 만들어줄 수 있다.
computed 속성에 대해서 function으로 선언하는 대신, mapState 내부에 선언하여 다양한 방법으로 간결하게 연결 할 수 있다.
new Vue({
el: '#app',
store,
data: {
message: 'Hello world',
localCount: 4
}
computed: {
messageWithName () {
return message + " Minju"
},
...mapState({
count: () => this.$store.state.count
countAlias: 'count',
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
}
});
혹은
...mapState(['count'])