Vue Vuex Getters

YEZI🎐·2022년 12월 12일
0

Vue

목록 보기
41/45

Getters

때로는 저장소 상태를 기반하는 상태를 계산(computed)해야 할 수 도 있다.
(ex. 아이템 리스트를 필터링하고 계산)

computed: {
  doneTodosCount () {
    return this.$store.state.todos.filter(todo => todo.done).length
  }
}

위 예시에서 둘 이상의 컴포넌트가 doneTodosCount를 사용 해야하는 경우,
함수를 복제하거나 공유된 헬퍼를 추출하여 여러 위치에서 가져와야 하는데 둘 다 이상적이지 않다.

Vuex를 사용하면 저장소에서 getters를 정의 할 수 있다.
저장소(store)computed 속성으로 생각할 수 있다.

computed 속성 속성처럼 getter의 결과는 종속성에 따라 캐쉬(cache)되고, 일부 종속성이 변경된 경우에만 다시 재계산된다.

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    // Getters는 첫 번째 전달인자로 상태를 받음
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})

속성 유형 접근

getters: {
  // ...
  // Getters는 두 번째 전달인자로 다른 getter를 받음
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}

getters는 store.getters 객체로 접근하고, 속성값에 접근하여 사용할 수 있다.

// 컴포넌트
computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}

메소드 유형 접근

함수를 반환하여 getter에 전달인자로 전달할 수도 있다.
이것은 저장소의 배열을 검색할 때 특히 유용하다.

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // output : { id: 2, text: '...', done: false }

메서드를 통해 접근하는 getter는 호출 할 때마다 실행되며 결과가 캐시되지 않는다는 것을 유의해야 한다.

mapGetters 헬퍼

mapGetters 헬퍼는 저장소 getter를 로컬 computed 속성에 매핑한다.

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
    // getter를 객체 전개 연산자로 계산하여 추가
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

getter를 다른 이름으로 매핑하려면 객체를 사용한다.

...mapGetters({
  // this.doneCount를 store.getters.doneTodosCount에 매핑
  doneCount: 'doneTodosCount'
})
profile
까먹지마도토도토잠보🐘

0개의 댓글