LoginSignup
1
1

More than 3 years have passed since last update.

Vue.jsとGoogle Books APIを使って本の検索機能を実装する

Last updated at Posted at 2021-02-16

Vue.jsとGoogle Books APIを使って簡単に本の検索機能が実装できたのでメモを残しておきます。

コード内容

    <form id="search-form">
        <input class="form-text" type="text" id="isbn" placeholder="ISBNコードを入力" v-model="isbn">
        <button type="button" v-on:click="search()">検索</button>
    </form>
    <div id="result"></div>

検索フォーム.png

に対して、


new Vue({
    el:'#search-form',
    data: {
        isbn: '',
    },
    methods: {
        search() {
            const code = document.getElementById('isbn').value;

            fetch(`https://www.googleapis.com/books/v1/volumes?q=isbn:${code}`)
                .then(response => {
                    return response.json();
                }).then(data => {
                    const bookTitle = data.items[0].volumeInfo.title;
                    $('#result').append(bookTitle);
                }).catch(function(error) {
                    $('#result').append(error);
                });
        }
    }
});

と設定することで
検索結果.png

検索機能が実装されました。

何が起きているのか

まず

const code = document.getElementById('isbn').value;

の部分で、検索フォームに入力されたISBNコードを取得しています。

 fetch(`https://www.googleapis.com/books/v1/volumes?q=isbn:${code}`)
                .then(response => {
                    return response.json();
                }).then(data => {
                    const bookTitle = data.items[0].volumeInfo.title;
                    $('#result').append(bookTitle);
                }).catch(function(error) {
                    $('#result').append(error);
                });

上記の部分でやっていることは,

①Fetch APIでPromiseを受け取る
②Promiseが成功すればresolveを失敗すればrejectを呼び出します。(詳しくはわかっておらずすみません、、、)
③resolveならthen,rejectならcatchの処理が行われる
④(resolveだった場合の処理)ここで受け取ったレスポンスの中からJSONを抽出
⑤JSONをdataと定義し、JSONを辿っていきtitleを取得!

といった流れになっています。

終わりに

自分で書いていて理解が足りていない部分が、よくわかりました(特にPromise)
間違っている点などあれば、ご指摘いただけると幸いです。

1
1
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
1
1