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
예시 )
let josh = {
field : 'web',
language : 'js'
};
let developer = {
nation : 'korea'
...josh
};
console.log(developer);
-> 원래는 이렇게 사용했었음
let developer = {
nation : 'korea',
field : josh.field,
language : josh.language
}
* mapState
-vuex에 선언한 state 속성을 뷰 컴포넌트에 더 쉽게 연결해주는 헬퍼
예시)
//App.vue
import {mapState} from 'vuex'
computed() {
...mapState(['num'])
// num() {return this.$store.state.num;}
}
//store.js
state : {
num : 10
}
// {{ this.$store.state.num}}
<p>{{ this.num}}</p> //10
* mapGetters
-vuex에 선언한 getters 속성을 뷰 컴포넌트에 더 쉽게 연결해주는 헬퍼
예시)
// App.vue
import {mapGetters} from 'vuex'
computed(){
...mapGetters(['reversMessage'])
}
//store.js
getters : {
reversMessage (state) {
return state.msg.split('').reverse().join('');
}
}
<p>{{ this. reversMessage }}</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에 선언한 속성을 그대로 컴포넌트에 연결하는 문법
예시)
//배열 리터럴
...mappMutations([
'clickBtn', // 'clickBtn' : clickBtn
'addNumber' // addNumber (인자)
])
- vuex에 선언한 속성을 컴포넌트의 특정 메서드에다가 연결하는 문법
//객체 리터럴
... mapMutations({
popupMsg : 'clickBtn' // 컴포너너트 메서드 명 : store의 뮤테이션 명
})