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>
に対して、
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);
});
}
}
});
検索機能が実装されました。
何が起きているのか
まず
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)
間違っている点などあれば、ご指摘いただけると幸いです。