Vuex의 요소를 더 쉽게 사용 - Helper

soplia080 gyp·2022년 2월 13일

Vue Js

목록 보기
16/18
  • Store에 있는 4가지 속성을 간편하게 코딩하는 방법
    • state -> mapState
    • getter -> mapGetters
    • mutations -> mapMutations
    • actions -> mapActions

ex) this.$store.state.변수명 -> 컴포넌트가 많아질수록 추척이 어려움.

  • 사용법
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

export default{
	computed() { ...mapStore(['num']), ...mapGetters(['countedNum']) },
  	methods : { ...mapMutations(['clickBtn']), ...mapActions(['asyncClickBtn']) }
}

... => ES6 Object Spread Operator

mapState

  • Vuex에서 선언한 state 속성을 뷰 컴포넌트에 쉽게 연결해주는 helper
// 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 속성을 뷰 컴포넌트에 쉽게 연결해주는 helper
// App.vue
import { mapGetters } from 'vuex'
computed(){
	...mapGetters(['reverseMessage'])
}
// store.js
getters: {
	reverseMessage(state){
    	return state.msg.split('').reverse().join('');
    }
}
<p>{{this.reverseMessage}}</p>
  • Object Spread Operator 쓰는 이유 : 기존의 computed()의 내부 속성과 mapGetters를 같이 쓰기 위함.

mapMutations

  • Vuex에서 선언한 mutations 속성을 뷰 컴포넌트에 쉽게 연결해주는 helper
// 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 속성을 뷰 컴포넌트에 쉽게 연결해주는 helper
// 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>

helper의 유연한 문법

  • vuex에 선언한 속성을 그대로 컴포넌트에 연결하는 문법
// 배열 리터럴
...mapMutations([
  // 'clickBtn': clickBtn -> ES6 키와 속성값이 같은 경우 축약형으로 됨.
	'clickBtn', 
   // addNumber(인자) mapMutataions의 좋은 점이 따로 인자 설정을 안해도 됨.
  	'addNumber', 
])
  • vuex에 선언한 속성을 컴포넌트의 특정 메서드에다가 연결하는 문법
// 객체 리터럴
...mapMutations([
   // 컴포넌트 메서드 명 : Store의 Mutataion명
	popupMsg : 'clickBtn' 
])
profile
배우면서 나아가자

0개의 댓글