써치킴의 우당탕탕 개발 블로그

[Vue.js][Ch4][영화검색 사이트] Vuex Helpers 본문

완벽하게 Vue.js

[Vue.js][Ch4][영화검색 사이트] Vuex Helpers

써치킴 2022. 5. 2. 17:37

about.vue > store에서 계산된 데이터를 반복적으로 가져와서 사용한다.

반복되는 코드를 간소화시킬 수 있는 상태관리 라이브러리를 제공하는 Vuex의 기능을 사용해보자.

구글에 vuex next 검색 > https://vuex.vuejs.org/ 이동 > Core Concepts > State > The mapState Helper 참고

The mapState Helper

state를 map을 이용해서 반복적으로 출력하여 computed 옵션에 등록

computed: mapState([
  // map this.count to store.state.count
  'count'
])

The mapGetters Helper

사용하고자 하는 데이터를 문자데이터로 명시해서 전개연산자로 풀어준다.

...mapGetters({
  // map `this.doneCount` to `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

1. import vuex

import { mapState } from 'vuex'

2. about.vue > computed 수정

computed: {
    // 함수 실행 결과가 반환되고 계산된 데이터처럼 객체 데이터 내부에 등록될 수  있도록 ... 전개 연산자 사용 
    ...mapState('about', [        // 인수 => store의 사용할 모듈 명시, 배열데이터 > 사용할 데이터 명시
      'image',
      'name',
      'email',
      'blog',
      'phone'
    ])
},
  • 함수 실행 결과가 객체 데이터로 반환되고, 전개연산자로 전개해서 computed라는 계산된 데이터에 등록하여 사용
  • 인수 => store의 사용할 모듈 명시, 배열데이터 > 사용할 데이터 명시

3. Header.vue 동일하게 수정

computed: {
    ...mapState('about', [        // 인수 => store의 사용할 모듈 명시, 배열데이터 > 사용할 데이터 명시
      'image',
      'name'
    ])
}

4. MovieList.vue 동일하게 수정

computed: {
    ...mapState('movie', [        // 인수 => store의 사용할 모듈 명시, 배열데이터 > 사용할 데이터 명시
      'movies',
      'message',
      'loading'
    ])
}

5. Movie.vue 동일하게 수정

computed: {
    ...mapState('movie', [        // 인수 => store의 사용할 모듈 명시, 배열데이터 > 사용할 데이터 명시
      'theMovie',
      'loading'
    ])
  },

action을 Helper로 등록

dispatch는 함수처럼 이용하는 것이기 때문에

mapActions Helper는 methods에 작성

 

 

 

 

 

1. mapActions import

import { mapState, mapActions } from 'vuex'

2. methods에 action 등록

 ...mapActions('movie', [  
  'searchMovieWithId'
]),
  • movie 모듈의 searchMovieWithId 등록

3. 기존 store의 dispatch 함수 대신 등록된 action 사용

//this.$store.dispatch('movie/searchMovieWithId', {
this.searchMovieWithId({
  // ex) movie/tt1234545
  id: this.$route.params.id   // 주소 부분의 파라미터에서 omdbID를 가져옴
});

Vuex Helper는 state 데이터를 등록하는 용도를 제외하곤 활용하는 것을 권장하지 않는다!

mapActions Helper를 사용하는 것보단,

dispatch는 함수를 사용하는 것이 더 직관적이기 때문에

Comments