Vue.jsのお勉強。
Vue.jsでお天気情報のAPIを叩いて情報を取得するサンプルです。
お天気情報APIは無料で利用できるOpenWeatherMap(→APIリファレンス)を使用します。
Vue.jsでインクリメントサーチを少し改造して、リストから都市をクリックすると、その都市のお天気情報を表示します。
サンプルはこちら。
(見た目は、手抜きです・・・)
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Cities</title>
</head>
<body>
<div id="app">
<!-- 都市が選択されていれば、お天気情報を表示する -->
<div v-if="selectedCity" class="weather">
<p class="weather_city">
{{ city }}
</p>
<p class="weather_icon">
<img v-bind:src="icon" class="weather_icon">
</p>
<p class="weather_info">
{{ condition.main }}
</p>
<p class="weather_temp">
{{ temp }} °C
</p>
<button v-on:click="clearCity">
他の都市を表示
</button>
</div>
<!-- 都市が選択されていない場合、検索欄を表示する -->
<div v-else>
検索欄:<input type="text" v-model="searchQuery">
<ul v-for="city in filterCity">
<li v-bind:id="city" v-on:click="selectCity">{{ city }}</li>
</ul>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@0.18.0/dist/axios.min.js"></script>
<script src="main.js"></script>
</body>
</html>
JavaScript
var cityList = [];
$(function() {
$.getJSON("current.city.list.json")
.done(function(data) {
$(data).each(function() {
if( this.country === 'JP'){
cityList.push(this.name);
}
})
});
});
var app = new Vue({
el: '#app',
data: {
searchQuery: '', // 検索キーワード
cities: cityList,
selectedCity: '',
city: null,
temp: null,
condition: {
main: null
},
icon: ''
},
computed: {
filterCity: function(){
// 大文字・小文字の区別なく検索できるようにRegExpを使用する。
var self = this;
var matcher = new RegExp( this.searchQuery, 'i' );
return self.cities.filter(function (city) {
return matcher.test( city );
})
}
},
methods: {
// 都市名を選択したタイミングでお天気APIから情報を取得する。
selectCity: function(event) {
this.selectedCity = event.srcElement.id;
this.searchQuery = event.srcElement.id;
var getUrl = "https://api.openweathermap.org/data/2.5/weather?q=";
var getParam = ",jp&units=metric&appid=96ca6e792ced5ee2c084180cdc752c4d";
getUrl = getUrl + this.selectedCity + getParam;
axios.get(getUrl)
.then(function(response){
this.city = response.data.name
this.temp = response.data.main.temp
this.condition = response.data.weather[0]
this.icon = "https://openweathermap.org/img/w/" + response.data.weather[0].icon + ".png"
console.log(response);
}.bind(this))
.catch(function(error){
console.log(error)
})
console.log(event);
},
// 検索欄をクリアする。
clearCity: function(event) {
this.selectedCity = "";
this.searchQuery = "";
}
}
})


コメント