首先先到openweathermap.org的網站看一下我們要用的api
<script>
new Vue({
el: '#app',
data() {
return {
api_key: '申請的API_KEY',
base_url: 'https://api.openweathermap.org/data/2.5/',
city: '',
weatherData: {},
date: ''
}
},
methods: {
getWeather() {
var that = this;
axios.get(`${this.base_url}weather?q=${this.city}&units=metric&APPID=${this.api_key}`).then(response => {
console.log(response.data)
that.weatherData = response.data; // 更新weatherData
this.updateDate(); // 調用更新日期函數
}).catch(err => {
console.error(err);
});
},
updateDate() {
const currentDate = new Date();
const options = { year: 'numeric', month: 'long', day: 'numeric' };
this.date = currentDate.toLocaleDateString('en-US', options);
}
}
});
</script>
輸入內容(城市名稱)後按下enter,然後會看到像是這樣的回傳結果,我們需要的是main及weather、wind裡面的資料
接著加上
<body>
<div id="app">
<h1>天氣預報</h1>
<input type="text" v-model="city" @keyup.enter="getWeather">
<button @click="getWeather">獲取</button>
<div v-if="weatherData.main">
<h2>{{ weatherData.name }}</h2>
<p>日期: {{ date }}</p>
<p>天氣: {{ weatherData.weather[0].main }}</p>
<p>溫度: {{ weatherData.main.temp }}°C</p>
<p>濕度: {{ weatherData.main.humidity }}%</p>
<p>風速: {{ weatherData.wind.speed }} m/s</p>
</div>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</body>
</html>