Vue/Vuex

Vuex 핵심 컨셉(2) - Getters

고코모옹 2021. 7. 1. 15:25

- 둘 이상의 컴포넌트에서 Store 상태를 기반으로 computed를 계산해야 하는 경우
  (예: 아이템 리스트를 필터링하고 계산)

computed: {
  doneTodosCount () {
    return this.$store.state.todos.filter(todo => todo.done).length
  }
}
  • 함수 복제
  • 공유된 헬퍼를 추출하여 여러 위치에서 가져오기

=> 둘 다 이상적이지 않다.

 

- 위와 같은 경우 Vuex를 사용하여 Store에서 'getters'를 정의

  • Store의 computed 속성으로 생각할 수 있음
  • computed 속성처럼 getter의 결과는 종속성에 따라 캐쉬되고, 일부 종속성이 변경된 경우에만 다시 재계산
  • getters는 첫번째 전달인자로 상태(state)를 받는다.
const store = createStore({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos (state) {
      return state.todos.filter(todo => todo.done)
    }
  }
})

 

- 속성 유형 접근

  • store.getters 속성으로 값에 접근 가능
  • 두번째 전달인자로 다른 getter도 받을 수 있음
  • Vue의 반응성 시스템의 일부로 캐시된 것임을 유의해야 함
// store/index.js
getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}

// TodoList.vue
computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}

 

- 메소드 유형 접근

  • 함수를 반환하여 getter에 전달인자로 전달 가능
  • Store의 배열을 검색할 때 유용
  • 메서드를 통해 접근하는 getter는 호출 할 때마다 실행되며 결과가 캐시되지 않는다는 것에 유의
// store/index.js
getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

// TodoList.vue
this.$store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

 

[ 참고자료 ]

https://next.vuex.vuejs.org/guide/getters.html

 

Getters | Vuex

Getters Sometimes we may need to compute derived state based on store state, for example filtering through a list of items and counting them: computed: { doneTodosCount () { return this.$store.state.todos.filter(todo => todo.done).length } } If more than o

next.vuex.vuejs.org