2025-03-05-天氣查詢應用程式」的第 1 步:抓取氣象局 API 中指定的三個城市的資料

2025-03-05-天氣查詢應用程式」的第 1 步:抓取氣象局 API 中指定的三個城市的資料

我們來完成天氣查詢程式的 第 1 步:抓取氣象局 API 中指定的三個城市的資料


✅ 目標

成功從氣象局 API 中抓取以下三個城市的天氣資料,並儲存在 weatherData 中:

  • 臺北市
  • 臺中市
  • 高雄市

📁 WeatherQuery.vue 完整範例:第 1 步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<template>
<h2>🌦️ 天氣查詢(第 1 步)</h2>

<div>
<h3>目前抓到的城市資料:</h3>
<ul>
<li v-for="city in weatherData" :key="city.locationName">
✅ {{ city.locationName }}
</li>
</ul>

<pre>{{ weatherData }}</pre> <!-- 除錯用 -->
</div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const apiKey = '你的 API 金鑰'
const url = `https://opendata.cwa.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=${apiKey}`

const allCities = ['臺北市', '臺中市', '高雄市'] // 只取這 3 個城市
const weatherData = ref([]) // 存放抓到的天氣資料

onMounted(async () => {
try {
const response = await fetch(url)
const data = await response.json()

const locations = data.records.location

// 過濾三個指定城市的資料
weatherData.value = locations.filter(loc =>
allCities.includes(loc.locationName)
)
} catch (error) {
console.error('❌ 發生錯誤:', error)
}
})
</script>

✅ 驗收標準

執行畫面中應顯示:

  • ✅ 三筆城市名稱(臺北市 / 臺中市 / 高雄市)
  • <pre>{{ weatherData }}</pre> 可看到詳細的天氣資料(包含 weatherElement

🚀 下一步可以做什麼?

  • 建立 <select> 讓使用者選城市
  • 顯示該城市的天氣現象 / 溫度 / 降雨機率