[Vue] Vue를 사용한 TMDB API 사용하기

1. Vue TMDB API 키 받기

Vue.js에서 TMDB(The Movie Database) API를 사용하는 방법으로 API를 사용해 영화, TV 프로그램, 배우 정보 등을 가져올 수 있습니다. TMDB를 사용하려면 먼저 웹 사이트에 들어가 화원가입을하고 API 키를 발급 받아야합니다.

 

The Movie Database (TMDB)

환영합니다 수백만 개의 영화, TV 프로그램 및 인물을 발견하세요. 지금 살펴보세요.

www.themoviedb.org

TMDB 공식사이트에 들어가 화원가입 후 설정에 들어가 API키를 발급 받습니다. 발급받은 API를 복사한 후 먼저 Vue 프로젝트를 생성하기 위해 아래 명령어를 입력해 Vue 프로젝트를 생성합니다.

vue create tmdb-vue

2. API 라이브러리 설치 

다음 생성한 프로젝트에 들어가 vscode로 실행한 후 API를 호출하기위한 Axios 라이브러리를 설치합니다.

cd tmdb-vue
npm install axios && yarn add axios

3. 환경 변수 설정

프로젝트 디렉토리에 .env 파일을 생성하고 환경변수에 저장할 API 키를 넣어줍니다.

VUE_APP_TMDB_API_KEY=your_api_key_here

4. TMDB API 호출

프로젝트 폴더에 src/components 폴더로 가 MovieList.vue 컴포넌트를 생성하고, TMDB API를 호출하는 코드를 작성해줍니다. 

<template>
  <div>
    <h1>Movie List</h1>
    <ul>
      <li v-for="movie in movies" :key="movie.id">{{ movie.title }}</li>
    </ul>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      movies: [],
    };
  },
  created() {
    this.fetchMovies();
  },
  methods: {
    async fetchMovies() {
      try {
        const response = await axios.get(
          `https://api.themoviedb.org/3/movie/popular?api_key=${process.env.VUE_APP_TMDB_API_KEY}&language=ko-KR`
        );
        this.movies = response.data.results;
      } catch (error) {
        console.error("Movie List Error", error);
      }
    },
  },
};
</script>

5. 컴포넌트 사용

src/App.vue 파일에서 MovieList 컴포넌트를 사용합니다.

<template>
  <div id="app">
    <MovieList />
  </div>
</template>

<script>
import MovieList from "./components/MovieList.vue";

export default {
  components: {
    MovieList,
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

6. 실행

프로젝트를 실행해 결과를 확인합니다.

yarn serve

7. 포스터 띄우기

src/componenst 폴더에 MovieList.vue 돌아가 이번에는 영화포스터를 띄워봅니다.

<template>
  <div>
    <h1>Movie List</h1>
    <div class="movies">
      <div class="movie" v-for="movie in movies" :key="movie.id">
        <img :src="getPosterUrl(movie.poster_path)" alt="" />
        <h1>{{ movie.title }}</h1>
        <p>{{ movie.release_date }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      movies: [],
    };
  },
  created() {
    this.fetchMovies();
  },
  methods: {
    async fetchMovies() {
      try {
        const response = await axios.get(
          `https://api.themoviedb.org/3/movie/popular?api_key=${process.env.VUE_APP_TMDB_API_KEY}&language=ko-KR`
        );
        this.movies = response.data.results;
      } catch (error) {
        console.error("Movie List Error", error);
      }
    },
    getPosterUrl(posterPath) {
      if (!posterPath) {
        return "https://via.placholder.com/200x300?text=No+Image";
      }
      return `https://image.tmdb.org/t/p/w500${posterPath}`;
    },
  },
};
</script>

<style>
.movie-list {
  text-align: center;
}
.movies {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  padding: 2px;
}
.movie {
  margin: 5px;
}
img {
  width: 200px;
  height: 300px;
  border-radius: 10px;
}

h1 {
  font-size: 1.2em;
}
</style>

 

 

GitHub - Koras02/vue-tmdb

Contribute to Koras02/vue-tmdb development by creating an account on GitHub.

github.com

 

LIST

'Front-End > VueJS' 카테고리의 다른 글

[Vue] 6장(완) API 통신  (0) 2025.03.16
[Vue] 5장 상태관리  (0) 2025.03.08
[Vue] 4장 라우팅  (0) 2025.03.05
[Vue] 3장 리스트와 키  (0) 2025.02.28
[Vue] 2장 기본 컴포넌트  (0) 2025.02.23