[Vue.js] Vuex - (2) Helper 함수
이번에는 Vuex에서 Store의 상태, getter, 메서드들을 좀 더 용이하게 사용하는 Helper 함수에 대해 알아보겠다.
* 이 글은 캡틴판교님의 Vue.js 강의 및 블로그를 기반으로 학습한 내용을 정리하고 있습니다.
💚 Helper 함수란?
Vuex의 내장함수로, Store의 아래 네 가지 속성을 간편하게 코딩하는 방법이다. (Synthetic Sugar에 해당)
- state => mapState
- getters => mapGetters
- mutations => mapMutations
- actions => mapActions
- 사용법
// App.vue
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
computed() {
...mapState(['num']),
...mapGetters(['countedNum'])
},
methods: {
...mapMutations(['clickBtn']),
...mapActions(['asyncClickBtn'])
}
}
vuex에서 각 Helper 함수를 가져와서 사용하면 된다. 필요한 속성의 키값을 배열로 입력하고, 객체 전개 연산자(ES6문법)로 적용한다.
computed() {
...mapState(['num', 'str']),
}
// 해석
computed() {
num: // value,
str: // value,
}
- 사용 예시
1) mapState
Vuex에 선언한 state 값을 Vue 컴포넌트에 더 쉽게 연결해주는 헬퍼 함수. data() 가 아닌 computed() 에 전개연산자로 선언.
// App.vue
import { mapState } from 'vuex'
computed: {
// num() { return this.$store.state.num; }
...mapState(['num'])
}
// <p>{{ this.$store.state.num }}</p>
<p>{{ this.num }}</p>
2) mapGetters
Vuex에 선언한 getters 계산된 상태값을 Vue 컴포넌트에 더 쉽게 연결해주는 헬퍼 함수. 마찬가지로 computed() 에 선언한다,
// App.vue
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['reverseMsg'])
}
// <p>{{ this.$store.getters.reverseMsg }}</p>
<p>{{ this.reverseMsg }}</p>
3) mapMutations, mapActions
Vuex에 선언한 동기(mutations), 비동기(actions) 메서드들을 Vue 컴포넌트에 더 쉽게 연결해주는 헬퍼 함수.
컴포넌트의 methods 필드에 선언하며, 마찬가지로 전개연산자를 활용하여 연결할 수 있다.
// App.vue
import { mapMutations, mapActions } from 'vuex'
methods: {
...mapMutations(['clickBtn']),
...mapActions(['asyncClickBtn']),
}
// store.js
mutations: {
clickBtn(state) {
alert(state.msg);
}
},
actions: {
asyncClickBtn(context) {
setTimeout(() => context.commit('clickBtn'), 2000);
}
}
<button @click="clickBtn>click</button>
<button @click="asyncClickBtn>async click</button>
* 메서드명 재지정
헬퍼 함수들을 활용할 때, store에 설정한 상태, 메서드명과 다르게 설정할 경우 배열이 아닌 객체형태로 설정할 수 있다.
이 때, key 값이 컴포넌트에서 활용하고자 하는 상태, 메서드명이 될 것이다.
methods: {
...mapMutations({
localMethod: 'globalMethod',
})
}
확실히 react-redux 문법과 느낌이 비슷하다고 생각됬다.
장점은 Redux는 useSelector(상태)는 콜백, useDispatch(메서드)는 액션을 넘기는 등 문법이 가지각색이라면,
Vuex의 경우엔 모든 필드(state, getters, 메서드들)의 문법이 일관적이라는 장점이 있기 때문에, Vue의 장점인 통일성이 좀 더 부각됬다.
이제 Vue 프로젝트에 필요한 기본적인 내용은 어느정도 진행되었고, 이후 강의는 Vue로 실제 구현을 하면서 팁내용을 정리하려고 한다.