LoginSignup
9
8

More than 3 years have passed since last update.

Vue.jsで超簡易的な映画検索アプリを作ってみた

Last updated at Posted at 2020-07-09

はじめに

この記事は『2020年のフロントエンドマスターになりたければこの9プロジェクトを作れ 』で紹介されていた

最初の
「Build a movie search app using React (with hooks)」 = Reactを使って映画検索アプリを作成する
というものをVue.js(Vue CLI)で簡易的に作ってみたものです。

完成したもの

search-movie.gif

この8ビット風のcssはNES.cssを利用させていただきました!

スクリーンショット 2020-07-09 22.28.38.png

APIについて

OMDb APIという映画検索APIを用いました。

https://www.omdbapi.com/?apikey=[yourkey]&s=hero

s=[検索したい文字列]で下記のようなjsonが返ってきます。

スクリーンショット 2020-07-09 22.22.28.png

※映画のポスター画像も取得できるのが便利です!

コード

Vue.js

vue-magic-gridと呼ばれる簡単にタイル状に並べてくれるライブラリを用います。

Movie.js
import MagicGrid from 'vue-magic-grid'
import Vue from 'vue'

let baseUrl = 'https://www.omdbapi.com/?apikey=[yourkey]'
export default {
  name: 'movie',
  data () {
    return {
      searchStr: '',
      results: []
    }
  },
  methods: {
    // クリック時発火
    onClick: function() {
      // 何も入力されていない場合はAPI叩かない
      if (this.searchStr === '') {
          return
      }
      // 検索用のURL作成
      baseUrl = baseUrl + '&s=' + this.searchStr
      // axiosで非同期通信
      this.axios.get(baseUrl)
      .then(response => {
          this.results = response.data.Search
          Vue.use(MagicGrid)
      })
    }
  }
}

HTML&CSS

v-modelを用いてテキストボックスの値(searchStr)を双方向データバインディングします。
ボタンでAPIを叩いて結果を表示してます。

<div class="movie">
  <!-- 検索ボックス -->
  <div class="nes-field search-box">
      <input type="text" id="name_field" class="nes-input search-box__input" v-model="searchStr" placeholder="enter movie title" />
      <button type="button" class="nes-btn search-box__btn" @click="onClick">Search</button>
  </div>

  <magic-grid class="posts-list">
    <!-- 単体 -->
    <div class="posts-item nes-container with-title is-centered" v-for="(post, index) in results" :key="index">
      <p class="title">{{post.Title}}</p>
      <p>{{post.Year}}</p>
      <img :src="post.Poster" :alt="post.Title">
    </div>
  </magic-grid>
</div>
.search-box {
  display: flex;
  &__input {
    width: 80%;
  }
  &__btn {
    width: 20%;
  }
}
.posts-list {
  margin-top: 2.5rem;
}
.posts-item {
  img {
    width: 100%;
  }
}

終わり

こんな感じで映画のポスター付きで表示することができます!
コードはこちら

screencapture-localhost-8080-movie-2020-07-09-23_05_52.png

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8