Helper란?

JongIk Park·2021년 11월 23일
0

Vue.js

목록 보기
8/11
post-thumbnail

mapState, mapGetters, mapMutations, mapActions

mapState

  • Vuex에 선언한 state 속성을 뷰 컴포넌트에 더 쉽게 연결해주는 헬퍼
//App.vue
<!-- <p>{{ this.$store.state.num }}</p> -->
<p>{{ this.num }} </p>

import { mapState } from 'vuex'

computed(){
  ...mapState(['num'])
  /**
  num() {
  	return this.$store.state.num;
  }
  */
  
// store.js
state: {
  num: 10
}

mapGetters

  • Vuex에 선언한 getters 속성을 뷰 컴포넌트에 더 쉽게 연결해주는 헬퍼
//App.vue
<p>{{ this.reverseMessage }}</p>
// <p>{{ this.$store.getters.reverseMessage }}</p>

import { mapGetters } from 'vuex'
computed() {
  ...mapGetters(['reverseMessage'])
}

//store.js
getters: {
  reverseMessage(state) {
    return state.msg.split('').reverse().join('');
  }
}

mapMutations

  • Vuex에 선언한 mutations 속성을 뷰 컴포넌트에 더 쉽게 연결해주는 헬퍼
//App.vue
<button @click="clickBtn">popup message</button>

import { mapMutations } from 'vuex'

methods: {
  ...mapMutations(['clickBtn']),
  authLogin() {},
  displayTable() {}
}

//store.js
mutations: {
  clickBtn(state) {
    alert(state.msg);
  }
}

mapActions

  • Vuex에 선언한 actions 속성을 뷰 컴포넌트에 더 쉽게 연결해주는 헬퍼
//App.vue
<button @click="delayClickBtn">delay popup message</button>

import { mapActions } from 'vuex'

methods:{
  ...mapActions(['delayClickBtn']),
}

 //store.js
actions:{
  delayClickBtn(context) {
    setTimeout(() => context.commit('clickBtn'),2000);
  }
}

Helper의 사용법

  • 헬퍼를 사용하고자 하는 vue 파일에서 아래와 같이 해당 헬퍼를 로딩
//App.vue
// import { mapState, mapGetters, mapMutations, mapActions } from 'vuex' 와 동일
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'])
  }
// ... = Object Spread Operator

출처 : inflearn) Vue.js 중급 강좌 - 장기효

profile
신입 프론트엔드 개발자

0개의 댓글