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

[Vue.js][Ch4][영화검색 사이트] 단일 영화 상세 정보 가져오기 본문

완벽하게 Vue.js

[Vue.js][Ch4][영화검색 사이트] 단일 영화 상세 정보 가져오기

써치킴 2022. 4. 25. 20:31

OMDb API -> By ID or Title

i 파라미터를 사용하여 영화의 상세 정보를 요청해서 가져올 수 있다.

this.$route

현재 페이지 주소의 정보를 가져온다.

 

1. 영화 정보를 가져오는 _fetchMovie 함수의 url 구분

function _fetchMovie(payload) {
  const {title, type, year, page, id} = payload;
  const OMDB_API_KEY = '7035c60c';
  // id가 있으면 영화 상세 정보 요청
  // id가 없으면 영화 검색
  const url = id
              ? `https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&i=${id}` 
              : `https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&s=${title}&type=${type}&y=${year}&page=${page}`;

  return new Promise((resolve, reject) => {
    axios.get(url)
      .then(res => {
        if (res.data.Error) {   // 응답받은 영화정보 데이터에 에러가 있다면 예외처리
          reject(res.data.Error);
        }
        resolve(res);           // 정상동작하면 결과값 반환
      })
      .catch(err => {
        reject(err.message);    // 에러 반환
      })
  })

}
  • payload에  id가 있으면 영화 상세 정보 요청, id가 없으면 영화 검색

2. state 옵션 > 영화 상세 정보 변수 추가

theMovie: {}                              // 영화 상세 정보

3. movie.js > 영화의 상세 정보를 요청하는 함수 생성 

/*
* searchMovieWithId : ID를 이용해 영화 상세 정보를 가져옴
*/
async searchMovieWithId({ state, commit }, payload) {
  if(state.loading) return; // 로딩 중이면 함수를 빠져나감 (동작 중복 제거)

  commit('updateState', {  
    theMovie: {},           // 기존 영화 상세 정보 초기화
    loading: true           // 로딩 중인 상태로 만듦
  });

  try {
    const res = await _fetchMovie(payload);
    commit('updateState', {  
      theMovie: res.data
    });
  } catch (error) {
    commit('updateState', {  
      theMovie: {}
    });
  } finally {
    commit('updateState', {  
      loading: false           // 로딩 끝
    });
  }
}

4. Movie.vue > dispatch 메소드를 이용해 movie 모듈의 movie/searchMovieWithId 함수 실행

<template>
  <h1>Movie!</h1>
</template>

<script>
export default {
  created() {      // Movie 컴포넌트가 실행되면
    console.log(this.$route);     // 현재 페이지 주소 정보를 가져옴
    this.$store.dispatch('movie/searchMovieWithId', {
      // ex) movie/tt1234545
      id: this.$route.params.id   // 주소 부분의 파라미터에서 omdbID를 가져옴
    });
  }
}
</script>

5. Header.vue > Movie 네비게이션의 경로 변경

{
  name: 'Movie',
  href: '/movie/tt4520988'
},

6. routes > index.js 수정

{
  path: '/movie/:id',
  component: Movie
},

출력

Console에 뽑아보면

Comments