1.首先,你需要注册一个OpenWeatherMap账号,获取一个API密钥
-
安装axios来处理HTTP请求。
-
npm install axios pnpm install axios yarn axios
2.在Vue组件中使用axios发送请求并获取天气数据
-
-
<div> <p v-if="weatherData"> <strong>城市:</strong> {{ weatherData.name }}, {{ weatherData.sys.country }}<br> <strong>温度:</strong> {{ Math.round(weatherData.main.temp) }}°C<br> <strong>气压:</strong> {{ weatherData.main.pressure }} hPa<br> <strong>湿度:</strong> {{ weatherData.main.humidity }} %<br> <strong>天气:</strong> {{ weatherData.weather[0].description }} </p> <p v-else> 加载中... </p> </div>
-
-
import { onMounted, ref } from 'vue' import axios from 'axios' const weatherData = ref(null) onMounted(async () => { try { const apiKey = 'APIKEY' // 替换为你的API密钥 const url = `http://api.openweathermap.org/data/2.5/weather?q=安康&appid=${apiKey}&units=metric` const response = await axios.get(url) weatherData.value = response.data } catch (error) { console.error('Error fetching weather:', error) } })