2025-02-08- JavaScript 系列八:第6課 ── 天氣查詢應用程式-步驟02

2025-02-08- JavaScript 系列八:第6課 ── 天氣查詢應用程式-步驟02

接下來的目標是:

✅ 目標

WeatherQuery.vue 中完成一個具備以下功能的天氣查詢 App:

  • 「縣市」下拉選單

  • 顯示該縣市的:

    • 天氣現象
    • 最高溫度
    • 最低溫度
    • 降雨機率

🔧 建議步驟

✅ 1. 先去中央氣象局註冊並取得 API Key

前往 https://opendata.cwb.gov.tw/index,註冊後取得一組「授權碼 (Authorization)」。


✅ 2. API 測試網址(可用 fetch 測試)

1
https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=你的API_KEY&locationName=臺北市

🧱 WeatherQuery.vue 初始版結構範例(可直接用)

這是最簡單可運作的版本,之後我們再加強功能與樣式:

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<script setup>
import { ref, watch } from 'vue'

const cities = ['臺北市', '新北市', '桃園市', '臺中市', '臺南市', '高雄市']
const selectedCity = ref('臺北市')

const weatherInfo = ref(null)

const fetchWeather = async () => {
const apiKey = '你的 API KEY'
const url = `https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=${apiKey}&locationName=${selectedCity.value}`

try {
const res = await fetch(url)
const data = await res.json()
const location = data.records.location[0]

const elements = location.weatherElement
weatherInfo.value = {
description: elements[0].time[0].parameter.parameterName, // 天氣現象
minTemp: elements[2].time[0].parameter.parameterName, // 最低溫
maxTemp: elements[4].time[0].parameter.parameterName, // 最高溫
rain: elements[1].time[0].parameter.parameterName // 降雨機率
}
} catch (error) {
console.error('讀取失敗:', error)
}
}

// 自動偵測縣市選擇改變時重新取得天氣資料
watch(selectedCity, fetchWeather)

// 初始載入資料
fetchWeather()
</script>

<template>
<div>
<h2>天氣查詢</h2>
<label>選擇縣市:
<select v-model="selectedCity">
<option v-for="city in cities" :key="city" :value="city">{{ city }}</option>
</select>
</label>

<div v-if="weatherInfo">
<p>天氣現象:{{ weatherInfo.description }}</p>
<p>最高溫度:{{ weatherInfo.maxTemp }}°C</p>
<p>最低溫度:{{ weatherInfo.minTemp }}°C</p>
<p>降雨機率:{{ weatherInfo.rain }}%</p>
</div>
</div>
</template>

<style scoped>
label {
font-weight: bold;
margin-bottom: 1rem;
display: block;
}
</style>