1 minute read


1. 헬퍼함수란(Helper)?

헬퍼함수란 Vuex 기술 요소들을 컴포넌트에서 더 편하게 사용하도록 도와주는 API로 Vuex의 내장되어 있는 함수이다.
총 4가지의 함수가 있는데 하나씩 알아보도록 하자.


2. 기본 사용법

1
2
3
4
5
6
7
8
9
10
11
12
13
// App.vue
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

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

vuex에서 각 Helper 함수를 가져와서 사용하면 된다. 필요한 속성의 키값을 배열로 입력하고, 객체 전개 연산자(ES6문법)로 적용한다.


2.1 mapState

Vuex에 선언한 state 값을 Vue 컴포넌트에 더 쉽게 연결해주는 헬퍼 함수. data() 가 아닌 computed() 에 전개연산자로 선언한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
import { mapState } from 'vuex'

state : {
  num : 10
}

computed(){
  ...mapState(['num']),
  //num(){ return this.$store.state.num; }
}

// <p></p>
<p></p>


2.2 mapGetters

Vuex에 선언한 getters 계산된 상태값을 Vue 컴포넌트에 더 쉽게 연결해주는 헬퍼 함수. 마찬가지로 computed() 에 선언한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { mapGetters } from 'vuex'
 
computed() { ...mapGetters(['reverseMessage']) }
 
// store.js
getters: {
  reverseMessage(state) {
    return state.msg.split('').reverse().join('');
  }
}

//<p></p>
<p></p>


2.3 mapMutations

Vuex에 선언한 동기(mutations) 메서드들을 Vue 컴포넌트에 더 쉽게 연결해주는 헬퍼 함수. 컴포넌트의 methods 필드에 선언하며, 마찬가지로 전개연산자를 활용하여 연결할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { mapMutations } from 'vuex'
 
methods: {
  ...mapMutations(['clickBtn']),
  authLogin() {},
  displayTable() {}
}
 
// store.js
mutations: {
  clickBtn(state) {
    alert(state.msg);
  }
}

<button @click="clickBtn">popup message</button>


2.4 mapActions

Vuex에 선언한 비동기(actions) 메서드들을 Vue 컴포넌트에 더 쉽게 연결해주는 헬퍼 함수. mapMutations와 마찬가지로 컴포넌트의 methods 필드에 선언하며 전개연산자를 활용하여 연결할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { mapActions } from 'vuex'
 
methods: {
  ...mapActions(['delayClickBtn'])
}
 
// store.js
actions: {
  delayClickBtn(context) {
    setTimeout(() => context.commit('clickBtn'), 2000);
  }
}

<button @click="delayClickBtn">delay popup message</button>


3. 메서드명 재지정

헬퍼 함수들을 활용할 때, store에 설정한 상태, 메서드명과 다르게 설정할 경우 배열이 아닌 객체형태로 설정할 수 있다. 이 때, key 값이 컴포넌트에서 활용하고자 하는 상태, 메서드명이 될 것이다.

1
2
3
4
5
methods: {
  ...mapMutations({
    localMethod: 'globalMethod',
  })
}