jiwoolee.space
Vuex helpers (mapState, mapGetters) 본문
Vuex를 하다보니 너무 어렵다
속상해하지마
Vuex의 각 속성들을 더 쉽게 사용하게 해주는 helper가 있다
store에 있는 4가지 속성의 코딩을 쉽게 도와준다
- state => mapState
- getters => mapGetters
- mutations => mapMutations
- actions => mapActions
코딩을 쉽게 도와준다는데. 알차게 써야지.
helper 사용법
- helper를 사용하려고 하는 vue파일에 helper를 로딩해준다
import { mapState } from 'vuex';
import { mapGetters } from 'vuex';
import { mapMutations } from 'vuex';
import { mapActions } from 'vuex';
helper를 사용하지 않아도 state에 정의된 것에 접근할 수는 있다
나는 한번 실패했으니 쉽다는 helper로 가보려고.
mapState, mapGetters
mapState:
- state 속성을 뷰 컴포넌트에 쉽게 연결해주는 helper
- vuex store에 선언된 state에 this.$store.state로 접근하지 않아도 된다
- vue 템플릿에서 state안에있는 num 접근할 때도 this.num으로 바로 접근 가능
- mapState 함수를 가져와서 => ...연산자로 연결하고 => 배열리터럴로 확장해서 사용
그러니까,
배열 리터럴은 0개 이상의 식(expression) 목록이고,
...연산자는 ES6의 Object Spread Operator이다.
Spread 구문(...)을 사용하면
=> 배열이나 문자열과 같이 반복 가능한 문자를
=> 0개 이상의 인수(함수 호출할 경우) 또는 요소(배열 리터럴의 경우)로 확장해
=> 0개 이상의 key-value 쌍의 객체로 확장시킬 수 있다는 장점이 있다
Vuejs를 위한 ES6 내용
https://github.com/namjunemy/TIL/blob/master/Vue/es6_for_vuejs.md
GitHub - namjunemy/TIL: Today I Learned / 기억은 기록을 이길 수 없다.
:pencil:Today I Learned / 기억은 기록을 이길 수 없다. Contribute to namjunemy/TIL development by creating an account on GitHub.
github.com
특히 Object Spread Operator
https://github.com/namjunemy/TIL/blob/master/Vue/es6_for_vuejs.md#object-spread-operator
GitHub - namjunemy/TIL: Today I Learned / 기억은 기록을 이길 수 없다.
:pencil:Today I Learned / 기억은 기록을 이길 수 없다. Contribute to namjunemy/TIL development by creating an account on GitHub.
github.com
예를 들어,
// App.vue
import { mapState } from 'vuex';
computed() {
...mapState(['num'])
}
// store.js
state: {
num: 10
}
이렇게 ...mapState를 이용하면 this.$store.state.num을 대신할 수 있지.
mapGetters:
- vuex에 선언한 getters 속성을 뷰 컴포넌트에 더 쉽게 연결해주는 helper
- 마찬가지로 vuex store에 선언된 getters에 this.$store.getters로 접근하지 않아도 된다
- getters는 기존의 computed 속성
예를 들어,
// App.vue
import { mapGetters } from 'vuex';
computed: {
...mapGetters(['reverseMessage'])
}
// store.js
getters: {
reverseMessage(state) {
return state.msg.split('').reverse().join('');
}
}
이렇게 mapGetters를 이용하면
template 구역에서 this.$store.getters.reverseMessage 라고 썼어야 하는걸
this.reverseMessage로 뚝딱 가능.
ES6 Spread 연산자를 쓰는 이유
- 싱글파일 컴포넌트 구조의 각 컴포넌트에서 정의된 computed 속성이 있을 것이고,
- 거기에 Vuex store에 정의된 getters를 사용해야하는 상황이 있을 것이다.
- 이때, ... 연산자를 통해 mapGetters를 연결해줘야 컴포넌트에서 computed 속성과 Vuex의 store에 등록된 getters를 함께 사용할 수 있다.
계속 읽으면서 이해해보자...
다음은 mapMutations, mapActions 알아보자.
'Frontend-Vuejs' 카테고리의 다른 글
Vuex helpers로 api 호출하기 (0) | 2021.08.04 |
---|---|
Vuex helpers (mapMutations, mapActions) (0) | 2021.08.03 |
Vuex helpers - parent,child와 mapGetters,mapMutations (0) | 2021.08.02 |
Vuex helpers - parent,child와 getters,mutations (0) | 2021.08.02 |
Vuex helpers - parent,child와 state (0) | 2021.08.02 |