vuex 에서 Store 4가지 속성을 아래와 같이 변경하여 간편하게 불러올 수 있다.
- state > mapState
- getters > mapGetters
- mutations > mapMutation
- actions > mapActions
단, helper 을 알아보기 전에 ES6의 Object Spread Operator 에 대해 미리 숙지해야한다.
ES6의 Object Spread Operator
사용은 ... 으로 하고
...
예시
let kim = {
field: 'back-end',
language: 'java'
};
let developer = {
nation: 'korea',
...kim
};
console.log(developer);
결과
[object Object] {
field: "back-end",
language: "java",
nation: "korea"
}
... 만으로 kim 의 내용을 developer에서 사용할 수 있다.
원래라면 kim.field, kim.language로 불러왔을 텐데!
Object Spread Operator를 쓰는 이유는 기존 속성을 함께 쓰기 위함인데, 그 예로 ...을 잠시 빼보겠다.
let kim = {
field: 'back-end',
language: 'java'
};
let developer = {
nation: 'korea',
kim
};
console.log(developer);
[object Object] {
kim: [object Object] {
field: "back-end",
language: "java"
},
nation: "korea"
}
helper 함수 사용
선언 :
// script내 export 위에 선언
import { mapState } from 'vuex'
import { mapGetters } from 'vuex'
import { mapMutations } from 'vuex'
import { mapActions } from 'vuex'
// 또는
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
사용 :
선언한 파일 내에서 mapState, mapGetters 는 computed 아래
mapMutations, mapActions는 methods 아래에 Object Spread Operator(...)을 사용해서 호출한다.
$store.~~ 길게 작성하지 않고 연결이 가능하다.
mapState
- Vuex 에 선언한 state 속성을 뷰 컴포넌트에 더 쉽게 연결
computed() {
...mapState(['num'])
//num() { return this.$store.state.num; }
}
<!-- <p>{{ this.$store.state.num }}</p> -->
<p>{{ this.num }}</p>
mapGetters
- Vuex 에 선언한 getters속성을 뷰 컴포넌트에 더 쉽게 연결
computed() {
...mapGetters(['reversMessage'])
}
getters: {
reverseMessage(state) {
return state.msg.split('').reverse().join('');
}
}
<!-- <p>{{ this.$store.getters.reverseMessage}}</p> -->
<p>{{ this.reverseMessage }}</p>
mapMutations
- Vuex 에 선언한 mutations속성을 뷰 컴포넌트에 더 쉽게 연결
methods: {
...mapMutations(['clickBtn']),
authLogin() {},
displayTable() {}
}
mutations: {
clickBtn(state) {
alert(state.msg);
}
}
<button @click="clickBtn">popup message</button>
mapActions
- Vuex 에 선언한 actions속성을 뷰 컴포넌트에 더 쉽게 연결
import { mapActions } from 'vuex'
methods: {
...mapActions(['delayClickBtn']),
}
actions: {
delayClickBtn(context) {
setTimeout(() => context.commit('clickBtn'), 2000);
}
}
<button @click="delayClickBtn">delay popup message</button>
헬퍼의 유연한 문법
- Vuex에 선언한 속성을 그대로 컴포넌트에 연결하는 문법
// 배열 리터럴
...mapMutations([
'clickBtn', // 'clickBtn': clickBtn
'addNumber' // addNumber(인자)
])
- Vuex에 선언한 속성을 컴포넌트의 특정 메서드에다가 연결하는 문법
//객체 리터럴
...mapMutations({
popupMsg: 'clickBtn' //컴포넌트 메서드 명 : Store의 mutation 이름
})
참고자료
'Front > Vue.js' 카테고리의 다른 글
ESlint error가 화면을 덮지 않게 설정해보자 (0) | 2023.05.08 |
---|---|
NVM으로 node 버전 변경을 해보자 (windows) (0) | 2023.05.08 |
npm run build 하고 발생하는 error:03000086 (0) | 2023.03.30 |
Vuex 설치하고 등록하기 (0) | 2023.03.24 |
Vue CLI 설치하고 프로젝트 파일 생성하기 (0) | 2023.03.22 |