jiwoolee.space
Vuex helpers (mapMutations, mapActions) 본문
지난 게시글에서는 mapState와 mapGetters를 살펴보았다.
오늘은 mapMutations, mapActions.
mapMutations:
Vuex에 선언한 mutations 속성을 뷰 컴포넌트에 쉽게 연결해주는 helper
예를 들어,
// App.vue
import { mapMutations } from 'vuex';
methods: {
...mapMutations(['clickBtn']),
authLogin() {},
displayTable() {}
}
// store.js
mutations: {
clickBtn(state) {
alert(state.msg);
}
}
라는 App.vue가 있고,
template에 <button @click="clickBtn">popup message</button> 가 있을 때,
- 컴포넌트에서 버튼을 클릭하면 => 컴포넌트의 methods에 clickBtn이 정의 되어있는 것 처럼 동작한다.
- => 실제로는 ...mapMutations를 통해서 Vuex Store에 등록된 함수 사용하는 거지.
- => Vuex에 정의된 state.msg가 alert로 뜨게 될 거다
mapActions:
Vuex에 선언한 actions 속성을 뷰 컴포넌트에 쉽게 연결해주는 helper
예를 들어,
// App.vue
import { mapActions } from 'vuex';
methods: {
...mapActions(['delayClickBtn'])
}
// store.js
actions: {
delayclickBtn(context) {
setTimeout(() => context.commit('clickBtn'), 2000);
}
}
라는 App.vue가 있고,
template에 <button @click="delayClickBtn">delay popup message</button> 가 있을 때,
- 마찬가지로 컴포넌트에서 버튼을 눌러서 methods에 등록된 delayClickBtn을 호출하고
- => methods에는 Spread Operator로 store의 actions에 정의된 delayClickBtn을 등록한다.
helper의 유연한 문법
- Vuex의 선언한 속성을 그대로 컴포넌트에 연결하는 문법
=> addNumber(인자)의 경우 배열리터럴로 넘기는 string에 선언을 안해도 알아서 넘겨줌
- Vuex에 선언한 속성을 컴포넌트의 특정 메서드에다가 연결하는 문법
=> 컴포넌트에서 사용하는 메서드와 Store의 Mutation 명이 다를 경우
=> 객체 리터럴을 사용해서 등록할 수 있음
예를 들면 이렇다
// 배열 리터럴
...mapMutations([
'clickBtn', //'clickBtn': clickBtn
'addNumber' //addNumber(인자)
])
// 객체 리터럴
...mapMutations({
popupMsg: 'clickBtn' // 컴포넌트 메서드 명 : Store의 Mutation 명
})
감이 오기 시작한다
'Frontend-Vuejs' 카테고리의 다른 글
Vuex helpers - parent,child와 actions,mapActions (0) | 2021.08.04 |
---|---|
Vuex helpers로 api 호출하기 (0) | 2021.08.04 |
Vuex helpers (mapState, mapGetters) (0) | 2021.08.03 |
Vuex helpers - parent,child와 mapGetters,mapMutations (0) | 2021.08.02 |
Vuex helpers - parent,child와 getters,mutations (0) | 2021.08.02 |