Vuex - Helper

바그다드·2023년 11월 19일
0

Store의 4가지 속성을 더 간편하게 코딩하게 하는 방법

사용법

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']) 
  }
}
  • ...mapState(['num'])
    Object Spread Operator로 ES6에서 지원하는 문법이다.
    num에 들어있는 모든 필드를 가지고 온다.

1. mapState

  • Vuex의 state를 컴포넌트에서 더 쉽게 연결해준다.
// App.vue
import { mapState } from 'vuex'

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

// store.js
state: {
	num: 10
}

// template
<!-- <p>{{this.$store.state.num}}</p> -->
<p>{{this.num}}</p>

2. mapGetters

  • Vuex의 getters를 컴포넌트에서 더 쉽게 연결해준다.
// App.vue
import { mapGetters } from 'vuex'

computed() { ...mapGetters(['reverseMessage'])}

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

// template
<!-- <p>{{this.$store.getters.reverseMessage}}</p> -->
<p>{{this.reverseMessage}}</p>

3. mapMutations

  • Vuex의 mutations를 컴포넌트에서 더 쉽게 연결해준다.
// App.vue
import {mapMutations} from 'vuex'

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

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

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

4. mapActions

  • Vuex의 actions를 컴포넌트에서 더 쉽게 연결해준다.
// App.vue
import { mapActions } from 'vuex'

methods: {
	...mapActions(['clickBtn'])
}

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

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

헬퍼의 유연한 문법

  1. vuex에 선언한 속성을 그대로 컴포넌트에 매칭하는 문법
// 배열 리터럴
...mapMutations([
	// 'clickBtn' : clickBtn
	'clickBtn', 
    // addNumber(인자) -> 따로 인자를 적지 않아도 자동으로 인자를 넘겨줌
    'addNumber'
])
  1. vuex에 선언한 속성을 컴포넌트의 메서드에 매칭하는 방법
// 객체 리터럴
...mapMutations({
	// 컴포넌트 메서드 : Store의 mutation
	popupMsg: 'clickBtn'
})
profile
꾸준히 하자!

0개의 댓글