axiosを使用してビットコイン情報を画面に表示してみた
はじめに
公式のページ参考:axios を利用した API の使用 — Vue.js
内容
CDNによるaxiosの読み込み
- Bodyタグの最後に記述
- vueファイルよりcdnを先に読み込まないとerrorがでる
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/axios@0.19.0/dist/axios.min.js"></script> <script src="js/main.js"></script>
HTML + JSテンプレ
html
<div id="app"> <div v-if="loading" v-cloak> Loding... </div> <div v-else > <section v-if="hasError" v-cloak> Error! 管理者に連絡してください </section> <section v-else> <div v-for="(v,k) in info" class="currency" v-cloak> {{k}} : {{v.rate_float | currencyDecimal}} </div> </section> </div> </div>
js
var app = new Vue({ el:'#app', data:{ info:null, hasError:false, loading:true }, mounted(){ var url = "https://api.coindesk.com/v1/bpi/currentprice.json" axios .get(url) // .then(function(response){ // this.info = response // }) .then(response => (this.info = response.data.bpi)) .catch(error => this.hasError = true) .finally(() => this.loading = false) }, filters:{ currencyDecimal(value){ return value.toFixed(2) } } })
エラーハンドリング
axiosのコールが失敗する例
mounted(){ var url = "https://api.coindesk.com/v1/bpi/currentprice.json" axios .get(url) // .then(function(response){ // this.info = response // }) .then(response => (this.info = response.data.bpi)) .catch(error => this.hasError = true) .finally(() => this.loading = false) }
- アロー関数で書いてます
- API叩いてレスポンス取得
axios .get(url) // .then(function(response){ // this.info = response // }) .then(response => (this.info = response.data.bpi))
- 「 Error! 管理者に連絡してください」と表示する処理
- 「Loading...」と表示する処理
.catch(error => this.hasError = true) .finally(() => this.loading = false)
filtersフック
filters:{ currencyDecimal(value){ return value.toFixed(2) } }
v-cloak
html
<section v-if="hasError" v-cloak> Error! 管理者に連絡してください </section>
[v-cloak]{ display:none; }
v-if
同じ階層の要素に対してifをつけると
//hasErrorがtrueならこのsection <section v-if="hasError" v-cloak> Error! 管理者に連絡してください </section> //hasErrorがfalseならこのsectionを表示する <section v-else> <div v-for="(v,k) in info" class="currency" v-cloak> {{k}} : {{v.rate_float | currencyDecimal}} </div> </section>