Getters

오민영·2022년 2월 16일
0

Vuex

목록 보기
3/5
post-thumbnail

Reference

Vuex 란?
What is Vuex?
Vuex 시작하기

state를 계산한 값을 사용해야 하거나, 중복된 코드를 반복 호출 하는 경우가 있다.

// 여러 컴포넌트에서 같은 로직을 비효율적으로 사용하고 있는 상황 

// App.vue
computed: {
	doubleCounter(){
		return this.$store.state.counter * 2;
	}
}

// Child.vue
computed: {
	doubleCounter(){
		return this.$store.state.counter * 2;
	}
}

getters를 사용해서 state에 대한 변이를 각 컴포넌트에서 진행하는게 아니라 Vuex에서 변이를 수행하고, 각 컴포넌트에서 state를 호출만 하도록 하게한다.

// store.js
export const store = new.Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    increaseCount(state){
      return ++state.count;
    }
  }
})

// Counter.vue
<template>
  {{ count }}
</template>
<script>
  export default{
	computed: {
      count(){
        return this.$store.getters.increaseCount
      }
    }
  }
</script>

위와같이 getters는 이름 그대로 반환 값이 있어야 한다. 이 반환값은 state 뿐만 아니라, 같은 getters가 될 수 도 있다.

getters: {
  increaseCount(state, getters){
    return getters.getCurCount;
  },
    getCurCount(state){
      return state.count;
    }
}

getters 는 따로 전달 인자를 받을 수 없다. 위에서 보여지는 increaseCount(state,getters){} 의 state, getters는 Vuex getters의 default 전달 인자로, 말 그대로 현재 state와 getters를 나타낸다.
state, getters, rootState, rootGetters 순서로 전달인자를 선언해준다.

getters: {
        increaseCount: (state) => (num) => {
            return state.count + num;
        },
    }

// 같은 의미
increaseCount: (function (state) {
  return function (num) {
    return state.count + num;
  };
});

mapGetters

Vuex에 내장된 helper함수인 mapGetters를 사용해서 직관적인 코드를 작성할 수 있다.
state와 동일하게 ES6의 문법 ... 을 사용해서 현재 컴포넌트 computed와 함께 사용할 수 있다.

computed: {
  ...mapGetters([
    'doneTodosCount',
    'anotherGetter',
    // ...
  ]), 
  anotherCounter(){
    // ...
  }
}
profile
이것저것 정리하는 공간

0개의 댓글