2025-02-11- JavaScript 系列八:第6課 ── 天氣查詢應用程式-步驟05
中央氣象署(CWA)的 F-C0032-001 短期天氣預報 API 支援全台 22 個縣市(locationName)。你可以從 API 回傳的 JSON 中取得 所有支援的城市清單,而不需要手動寫死城市名稱!
✅ 如何動態取得所有縣市名稱?
你可以這樣做:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const cities = ref([])
const fetchCities = async () => { const apiKey = '你的 API KEY' const url = `https://opendata.cwa.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=${apiKey}`
const res = await fetch(url) const data = await res.json() cities.value = data.records.location.map(loc => loc.locationName)
if (cities.value.length > 0 && !selectedCity.value) { selectedCity.value = cities.value[0] } }
|
然後在 onMounted
呼叫:
1 2 3 4
| import { onMounted } from 'vue' onMounted(() => { fetchCities() })
|
並將 <select>
的選項改為:
1 2 3
| <select v-model="selectedCity"> <option v-for="city in cities" :key="city" :value="city">{{ city }}</option> </select>
|
💡 優點:
- 動態載入 → 不怕未來新增縣市或更名
- 更乾淨的程式碼 → 不需手動列出城市清單