[TIL]0821-Vuex 헬퍼함수
각 속성들을 더 쉽게 사용하는 방법 - Helper
Store에 있는 아래 4가지 속성들을 간편하게 코딩하는 방법
- state -> mapState
- getters -> mapGetters
- mutations -> mapMutations
- actions -> mapActions
헬퍼의 사용법
- 헬퍼를 사용하고자 하는 vue파일에서 아래와 같이 해당 헬퍼를 로딩
// App.vue
import { mapState } from 'vuex'
import { mapGetters } from 'vuex'
import { mapMutations } from 'vuex'
import { mapActions } from 'vuex'
export default {
computed() { ...mapState(['num']), ...mapGetters(['countedNum']) },
methods: { ...mapMutations([clickBtn]), ...mapActions(['asyncClickBtn']) }
}
...은 ES6의 Object Spread Operator이다.
mapState
- Vuex에 선언한 state속성을 뷰 컴포넌트에 더 쉽게 연결 해주는 헬퍼
// App.vue
import { mapState } from 'vuex'
computed() {
...mapState(['num'])
// num() { return this.$store.state.num;}
}
// store.js
state: {
num: 10
}
<!-- <p>{{ this.$store.state.num }}</p> -->
<p>{{ this.num}}</p>
mapGetters
- Vuex에 선언한 getters속성을 뷰 컴포넌트에 더 쉽게 연결 해주는 헬퍼
// App.vue
import { mapGetters } from 'vuex'
computed() { ...mapGetters(['reverseMessage']) }
// store.js
getters: {
reverseMessage(state) {
return state.msg.split('').reverse().join('');
}
}
<!-- <p>{{ this.$store.getters.reverseMessage }}</p> -->
<p>{{ this.reverseMessage }}</p>
mapMutations
- Vuex에 선언한 mutations속성을 뷰 컴포넌트에 더 쉽게 연결 해주는 헬퍼
// App.vue
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['clickBtn']),
authLogin() {},
displayTable() {}
}
// store.js
mutations: {
clickBtn(state) {
alert(state.msg);
}
}
<button @click='clickBtn'>popup message </button>
mapActions
- Vuex에 선언한 actions속성을 뷰 컴포넌트에 더 쉽게 연결 해주는 헬퍼
// App.vue
import { mapActions } from 'vuex'
methods: {
...mapActions(['delayClickBtn']),
}
// store.js
actions: {
delayClickBtn(context) {
setTimeout(() => context.commit('clickBtn', 2000);
}
}
<button @click="delayClickBtn">delay popup message</button>
헬퍼의 유연한 문법
- Vuex에 선언한 속성을 그대로 컴포넌트에 연결하는 문법
// 배열 리터럴
...mapMutations([
'clickBtn', // 'clickBtn': clickBtn
'addNumber' // addNumber(인자)
])
- Vuex에 선언한 속성을 컴포넌트의 특정 메서드에다가 연결하는 문법
// 객체 리터럴
...mapMutations({
popupMsg: 'clickBtn' // 컴포넌트 메서드 명: Store의 뮤테이션 명
})
해당 TIL은 인프런 Vue.js 중급 강좌를 보고 정리한 글입니다.
Author And Source
이 문제에 관하여([TIL]0821-Vuex 헬퍼함수), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@sza0203/TIL0821저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)