ブログの投稿ログ

2021年
9月
8月
7月
6月

天気API取得してみた

今回はopenweathermapを使って天気を取得したいと思います。
最初にログインしてAPI Keyを取得してください

// main.jsにaxiosを定義

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import App from './App.vue'
 
Vue.use(VueAxios, axios)
<template>
  <div class="wrap">
    <p>今日の天気は{{ weather }}で、気温は{{ temp }}度です。</p>
    // クリックファンクションでデータを取得
    <button @click="getData()">今日の東京の天気を取得</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  // 出力する値を定義
  data() {
    return {
        weather: 'xxxx',
        temp: 'yyyy'
    }
  },
  methods: {
    // クリックイベント
    getData: async function(){
        // apiを定義
        const url = `https://api.openweathermap.org/data/2.5/weather?id=1850147&units=metric&appid=ここにOpenWeathermapのAPIキーを指定`;
        // axiosでエンドポイントを定義
        const response = await axios.get(url);
        // 天気を定義
        this.weather = response.data.weather[0].main;
        // 温度を定義
        this.temp = response.data.main.temp;
    },
  }, 
}
</script>