본문 바로가기
Dev/Vue.js

[Vue.js] Vuex - 헬퍼 함수

by dev_jsk 2020. 9. 14.
728x90
반응형

Helper

Vuex 기술 요소들을 컴포넌트에서 더 편하게 쓸 수 있도록 도와주는 API

 

종류

  • state -> mapState
  • getters -> mapGetters
  • mutations -> mapMutations
  • actions -> mapActions

사용법

// App.vue
import { mapState, mapGetters, mapMutations, mapAcations } from 'vuex'

export default {
  // this.$store.state.num == mapState(['num'])
  // this.$store.getters.countedNum == mapGetters(['countedNum'])
  computed() { ...mapState(['num']), ...mapGetters(['countedNum']) },
  methods: { ...mapMutations(['clickBtn']), ...mapActions(['asyncClickBtn']) }
}

// ... : ES6의 Object Spread Operator

* Object Spread Operator

 

전개 구문

전개 구문을 사용하면 배열이나 문자열과 같이 반복 가능한 문자를 0개 이상의 인수 (함수로 호출할 경우) 또는 요소 (배열 리터럴의 경우)로 확장하여, 0개 이상의 키-값의 쌍으로 객체로 확장시

developer.mozilla.org

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.$store.getters.reverseMessage }}</p> -->
<p>{{ this.reverseMessage }}</p>

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': clickBtn
  'addNumber' // addNumber(인자) 인자 생략 가능. 호출하는 쪽 인자 그대로 넘긴다.
])

Vuex에 선언한 속성을 컴포넌트의 특정 메서드에다가 연결하는 문법

// 객체 리터럴
...mapMutations({
  popupMsg: 'clickBtn' // 컴포넌트 메서드 명 : store의 mutation 명
})

 

728x90
반응형

'Dev > Vue.js' 카테고리의 다른 글

[Vue.js] Todo App 최종 리팩토링  (0) 2020.09.14
[Vue.js] Vuex - 프로젝트 구조화 및 모듈화  (0) 2020.09.14
[Vue.js] Vuex - 주요 기술 요소  (0) 2020.09.11
[Vue.js] Vuex  (0) 2020.09.11
[Vue.js] ES6  (0) 2020.09.11

댓글