이제 Vuex가 실제 애플리케이션에서 어떻게 사용되는지 보자.
시작하기 전에, 개발을 좀 더 쉽게 만들어주는 몇가지 유틸리티 기능에 대해 알아보자.
# mapper
1/ mapGetters
computed 프로퍼티인 counter가 있고, fingalCounter인 getter에 접근한다.
<!--TheCounter.vue-->
<template>
<h3>{{ counter }}</h3>
</template>
<script>
export default {
computed: {
counter() {
return this.$store.getters.finalCounter; //getter에 접근
},
},
};
</script>
저장소에 파고드는것 말고는 아무것도 하지 않는다.
만약 이 코드가 마음에 들지 않는다면, Vuex의 도움을 받을 수 있다.
→ mapGetters라는 함수!
- computed객체 내부에서 mapGetters 함수를 사용할 수 있다.
- computed 프로퍼티를 직접 정의하는 대신, 여기서 mapGetters를 호출하면 이것이 객체를 반환한다.
- three dot spread(...)를 사용하면 computed 프로퍼티 내부로 객체를 spread할 수 있다.
- 즉, mapGetters는 computed 프로퍼티에 병합되는 객체를 제공한다.
- mapGetters가 제공하는 객체는 computed 프로퍼티로 구성되어 있는 객체이며, 자동으로 정의된다.
여기서 어떤 computed 프로퍼티를 얻을 수 있을까?
mapGetters는 배열을 인수로 받는다. 여기에 게터 이름을 문자열로 나열하는데,
computed 프로퍼티로 받아와야하는 getter의 이름을 넣으면 된다.
따라서 이 경우에는 finalCounter가 되지만, 때에 따라 여러 개의 getter가 될 수 있다.
<!--TheCounter.vue-->
<script>
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters(['finalCounter']),
},
};
</script>
이제 컴포넌트에서 finalCounter 연산 프로퍼티를 제공하며 자동으로 finalCounter 게터를 가리킨다.
h3태그에 counter가 아닌 finalCounter로 변경한다.
finalCounter가 computed 프로퍼티의 이름이기 때문.
<template>
<h3>{{ finalCounter }}</h3>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters(['finalCounter']),
},
};
</script>
새로고침해보면 이전과 동일하게 작동한다.
mapGetters를 사용하면, 특히 컴포넌트에서 게터를 여러개 사용할 경우,
'this.$store.getters..' 이렇게 store를 불필요하게 파고들 필요 없이 코드를 효율적으로 작성할 수 있다.
state와 mutation도 비슷하게 사용할 수 있지만 이번에는 사용하지 않을 예정.
2/ mapActions
컴포넌트에 action을 매핑할 수 있는 mapActions을 살펴보자.
ChangeCounter.vue에서 메서드를 별도로 정의하고 싶지 않다고 가정해보자.
이 addOne이라는 메서드도 결국 store를 파고들어 일부 작업을 dispatch할 뿐이다.
그 대신, mapGetters와 마찬가지로 Vuex에서 mapActions를 불러올 거다.
- mapGetters와 마찬가지로 mapActions을 호출한다.
- 하지만 mapGetters와는 달리 computed가 아니라 methods 내부에서 호출한다.
- 그리고 마찬가지로 spread 연산자를 사용하여 메서드 객체와 병합한 객체를 가져온다.
- mapActions도 배열을 인수로 받는다.
- 그리고 이 컴포넌트에서 메서드로 하고싶은 action의 이름을 정의한다. 이 경우에는 'increment'이다.
- 이 배열에 'increase' 액션을 추가하여 두 액션을 모두 이 컴포넌트의 메서드에 매핑할 수도 있다.
이 메서드가 mapActions에 의해 생성된다.
<!--ChangeCounter.vue-->
<script>
export default {
methods: {
// addOne() {
// this.$store.dispatch('increment');
// },
...mapActions(['increment', 'increase'])
},
};
</script>
첫 번째 버튼에서 increment를 호출한다. 이것이 increment 액션을 위해 생성되는 메서드의 이름.
그리고 두 번째 버튼에서는 increase를 가리킨다.
increase에는 payload가 필요하다. payload를 인수로 전달하면 된다. 여기서는 값이 11인 객체를 넘겨준다.
<!--ChangeCounter.vue-->
<template>
<button @click="increment">Add 2</button>
<button @click="increase({ value: 11 })">Add 11</button>
</template>
<script>
import { mapActions } from 'vuex';
export default {
methods: {
...mapActions(['increment', 'increase']),
},
};
</script>
// App.vue
mutations: {
increment(state) {
state.counter = state.counter + 2;
},
increase(state, payload) {
state.counter = state.counter + payload.value;
},
},
actions: {
increment(context){
setTimeout(function() {
context.commit('increment');
}, 2000);
},
increase(context, payload){
context.commit('increase', payload);
},
},
'Add 11' 버튼도 잘 작동한다.
이제 action을 매핑할 수 있으며,
이를 통해 메서드를 자체적으로 만드는 시간을 절약할 수 있다.
## 매핑하는 또다른 방법
액션을 매핑하는 다른 방법도 있다.
기본으로 주어지는 이름이 마음에 들지 않을 경우, mapActions를 호출하여 배열을 전달하는 대신, 객체를 전달할 수 있다.
그 다음 컴포넌트에 포함하려는 메서드의 이름을 key로 정의할 수 있다.
그리고 이 메서드에 매핑되어야 하는 액션을 value로 넣어준다.
(노트: mapGetter()에서도 동일한 방법을 사용할 수 있다.)
<template>
<button @click="inc">Add 2</button>
<button @click="increase({ value: 11 })">Add 11</button>
</template>
<script>
import { mapActions } from 'vuex';
export default {
methods: {
...mapActions({
inc: 'increment',
increase: 'increase',
}),
},
};
</script>
increment 액션은 inc메서드에 매핑되고,
increase 액션은 increase 메서드에 매핑된다.
따라서 inc를 이용하여 increment 액션을 호출해야 한다.
다시 작동시켜보면 여전히 잘 작동한다.
mapActions와 mapGetters는 아주 유용하다.
** 출처: 모든 내용은 Udemy Vue-완벽가이드 강의를 기반으로 작성하였습니다.
'Vue.js' 카테고리의 다른 글
[Udemy Vue 완벽가이드 Section15] 222. 모듈로 저장소 구성하기 (0) | 2023.10.25 |
---|---|
[Udemy Vue 완벽가이드 Section15] 221. 예시: 더 많은 상태 추가하기 (0) | 2023.10.25 |
[Udemy Vue 완벽가이드 Section15] 219. 액션 "컨텍스트" 이해하기 (0) | 2023.10.25 |
[Udemy Vue 완벽가이드 Section15] 218. 액션(Actions)으로 비동기 코드 실행하기 (0) | 2023.10.25 |
[Udemy Vue 완벽가이드 Section15] 217. 게터(Getters) 소개-데이터를 얻는 더 나은 방법 (1) | 2023.10.25 |