LoginSignup
2
1

More than 1 year has passed since last update.

【Vue.js】Vue.jsでAPIを利用したアプリを作ってみた(天気アプリ)

Posted at

概要

Vue.jsを使い、かつAPIを利用したアプリを作成したいと思い、
以下の画像のような「天気アプリ」を作ってみました。

この記事では作成したアプリの機能、実際の実装コードについて説明していきます。
最後にコードの全量も載せているので
ぜひjsfiddleやローカル環境で挙動を確認してみてください。

名称未設定.png

アプリの機能

OpenWeatherMapのAPIを利用して、
東京の天気情報を表示するアプリです。

「情報を更新」ボタンを押下すると、
表示されている天気情報を更新することが可能です。

APIキーの取得

今回は前述の通りOpenWeatherMapで提供されているAPIを利用しています。

実装するにあたりAPIキーを取得する必要があるのですが、
その取得方法については以下の記事によくまとめられているので
是非そちらをご覧ください。

無料天気予報APIのOpenWeatherMapを使ってみる

ここからはコードの内容について簡単に見ていきます。

axiosの利用

APIからデータを取得してその内容を表示するためにaxiosを利用します。
Vue.jsの公式ドキュメントでもAPIの使用にはaxiosが推奨されています。

今回の実装ではaxiosをCDNで読み込ませて利用します、
具体的には以下のコードをHTMLファイルに組み込みます。

index.html
 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

axiosによる情報の取得を今回は2箇所で行っています。
1箇所目は初期表示時で、2箇所目は更新ボタン押下の処理です。
それぞれ以下のように書いていきます。

①「初期表示」
mountedライフサイクルフックを使用し、取得データをdataプロパティに反映させます。

script.js
    mounted: function(){
        axios.get('https://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp&units=metric&appid=取得したAPIキー')
        .then(function(response){
          this.weather = response.data.weather[0].main
          this.temp = response.data.main.temp
        }.bind(this))
        .catch(function(error){
          console.log(error)
        })
    }

②「更新ボタン押下」
①と同様の処理をupdateメソッド内で行います。

script.js
    methods: {
        update: function(){
            axios.get('https://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp&units=metric&appid=取得したAPIキー')
            .then(function(response){
              this.weather = response.data.weather[0].main
              this.temp = response.data.main.temp
            }.bind(this))
            .catch(function(error){
                console.log(error)
            })
        },
    }

コード全量

HTML側も合わせたコードの全量は以下の通りです。
cssを工夫すればもっとカッコいいアプリが作れると思うのですが実力不足でした。
デザイン面の勉強も頑張ります、、、

index.html
<head>
    <meta charset="UTF-8">
    <title>天気アプリ</title>
</head>
<body>
    <div id="app">
        <div class="text-area">
            <p class="title">今の東京の天気</p>
            <p>{{ weather }}</p>
            <p>{{ temp }}&deg;C</p>
            <button class="update-button" v-on:click="update()">情報を更新</button>
            <p>
                <a href="https://openweathermap.org/api">※提供:openweathermap</a>
            </p>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="script.js"></script>
</body>
<style scoped>
.text-area {
  text-align: center;
}
.title {
  color: #444444;
  font-size: 35px;
  font-weight:700; 
}
.update-button {
  font-size: 15px;
  padding: 3px 5px;
  border: none;
  -webkit-appearance: none;
  background:#666666;
  color: #eee;
  border-radius: 4px;
}
</style>
script.js
var app = new Vue({
    el: '#app',
    data: {
      weather: null,
      temp: null
    },
    mounted: function(){
        axios.get('https://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp&units=metric&appid=取得したAPIキー')
        .then(function(response){
          this.weather = response.data.weather[0].main
          this.temp = response.data.main.temp
        }.bind(this))
        .catch(function(error){
          console.log(error)
        })
    },
    methods: {
        update: function(){
            axios.get('https://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp&units=metric&appid=取得したAPIキー')
            .then(function(response){
              this.weather = response.data.weather[0].main
              this.temp = response.data.main.temp
            }.bind(this))
            .catch(function(error){
                console.log(error)
            })
        },
    },
});

参考

記事「無料天気予報APIのOpenWeatherMapを使ってみる」
記事「お天気アプリで学ぶVue.jsのAPI連携」
記事「Vue.jsで東京都の今日の天気を表示するWebサイトを作るコピペサンプル」

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