vue3显示实时天气
时间: 2023-12-05 22:40:34 浏览: 144
为了在Vue3中显示实时天气,你可以使用第三方API来获取天气数据,并将其显示在Vue组件中。以下是实现此目的的一些步骤:
1.注册一个免费的天气API服务,例如OpenWeatherMap或WeatherAPI。
2.在Vue组件中使用Axios或Fetch等库来获取天气数据。
3.将获取的数据绑定到Vue组件的模板中,以便将其显示给用户。
下面是一个简单的示例,演示如何在Vue3中显示实时天气:
```html
<template>
<div>
<h1>{{ city }}天气</h1>
<div v-if="loading">正在加载...</div>
<div v-else>
<p>温度:{{ temperature }}℃</p>
<p>天气状况:{{ description }}</p>
<p>湿度:{{ humidity }}%</p>
<p>风速:{{ windSpeed }}米/秒</p>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'Weather',
data() {
return {
city: '北京',
temperature: '',
description: '',
humidity: '',
windSpeed: '',
loading: true,
};
},
created() {
this.getWeather();
},
methods: {
async getWeather() {
try {
const response = await axios.get(
`https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=YOUR_API_KEY&units=metric`
);
this.temperature = response.data.main.temp;
this.description = response.data.weather[0].description;
this.humidity = response.data.main.humidity;
this.windSpeed = response.data.wind.speed;
this.loading = false;
} catch (error) {
console.error(error);
}
},
},
};
</script>
```
在上面的示例中,我们使用了OpenWeatherMap API来获取天气数据,并将其绑定到Vue组件的模板中。请注意,你需要将YOUR_API_KEY替换为你自己的API密钥。
阅读全文
相关推荐


















