vue实现天气预报
Vue 实现天气预报功能
获取天气 API
注册并申请免费的天气 API 服务,如和风天气、OpenWeatherMap 或心知天气。获取 API Key 用于数据请求。
创建 Vue 项目
使用 Vue CLI 创建新项目:

vue create weather-app
安装 Axios
在项目中安装 Axios 用于发送 HTTP 请求:
npm install axios
创建天气组件
在 src/components 目录下创建 Weather.vue 文件:

<template>
<div class="weather-container">
<h3>{{ city }}天气预报</h3>
<div v-if="weatherData">
<p>当前温度: {{ weatherData.temp }}°C</p>
<p>天气状况: {{ weatherData.condition }}</p>
<p>湿度: {{ weatherData.humidity }}%</p>
</div>
<div v-else>
加载中...
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
city: '北京',
weatherData: null,
apiKey: 'YOUR_API_KEY',
apiUrl: 'https://api.openweathermap.org/data/2.5/weather'
};
},
mounted() {
this.fetchWeatherData();
},
methods: {
async fetchWeatherData() {
try {
const response = await axios.get(`${this.apiUrl}?q=${this.city}&appid=${this.apiKey}&units=metric`);
this.weatherData = {
temp: Math.round(response.data.main.temp),
condition: response.data.weather[0].description,
humidity: response.data.main.humidity
};
} catch (error) {
console.error('获取天气数据失败:', error);
}
}
}
};
</script>
<style>
.weather-container {
padding: 20px;
border-radius: 8px;
background-color: #f5f5f5;
max-width: 300px;
margin: 0 auto;
}
</style>
在主应用中使用组件
修改 src/App.vue 文件:
<template>
<div id="app">
<Weather />
</div>
</template>
<script>
import Weather from './components/Weather.vue'
export default {
name: 'App',
components: {
Weather
}
}
</script>
运行项目
启动开发服务器查看效果:
npm run serve
功能扩展建议
- 添加城市搜索功能,允许用户输入不同城市
- 实现未来几天天气预报展示
- 添加天气图标显示
- 实现定位功能自动获取当前位置天气
- 添加温度单位切换功能(℃/℉)
注意事项
- 替换代码中的
YOUR_API_KEY为实际获得的 API 密钥 - 不同天气 API 返回的数据结构可能不同,需要根据实际 API 文档调整代码
- 考虑添加错误处理,如 API 请求失败或城市不存在的情况
- 生产环境中应将 API 密钥存储在环境变量中,不要直接写在代码里






