vue2写个天气预报
时间: 2023-12-15 16:32:00 浏览: 113
以下是一个使用Vue2编写的天气预报的示例:
```html
<template>
<div>
<h2>{{ city }}天气预报</h2>
<div v-if="loading">加载中...</div>
<div v-else>
<div v-if="error">{{ error }}</div>
<div v-else>
<div>当前温度:{{ temperature }}℃</div>
<div>天气状况:{{ description }}</div>
<div>风速:{{ windSpeed }}m/s</div>
<div>湿度:{{ humidity }}%</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
city: '北京',
loading: true,
error: '',
temperature: '',
description: '',
windSpeed: '',
humidity: ''
}
},
mounted() {
this.getWeather()
},
methods: {
getWeather() {
const apiKey = 'your_api_key'
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=${apiKey}&units=metric&lang=zh_cn`
fetch(apiUrl)
.then(response => response.json())
.then(data => {
if (data.cod === 200) {
this.loading = false
this.temperature = data.main.temp
this.description = data.weather[0].description
this.windSpeed = data.wind.speed
this.humidity = data.main.humidity
} else {
this.loading = false
this.error = data.message
}
})
.catch(error => {
this.loading = false
this.error = error.message
})
}
}
}
</script>
```
这个示例使用了Vue的数据绑定和生命周期函数,通过调用OpenWeatherMap的API获取天气数据,并将数据渲染到页面上。你可以根据自己的需要修改城市名称和API密钥。
阅读全文