vue实现天气
Vue 实现天气应用
获取天气 API
选择一个可靠的天气 API 服务,如 OpenWeatherMap、WeatherAPI 或和风天气。注册并获取 API Key,确保能够调用接口获取天气数据。例如,OpenWeatherMap 提供免费的基础天气数据接口。
创建 Vue 项目
使用 Vue CLI 或 Vite 初始化一个 Vue 项目。安装必要的依赖,如 axios 用于发送 HTTP 请求:
npm create vue@latest weather-app
cd weather-app
npm install axios
设计组件结构
拆分天气应用为多个组件,例如:

WeatherDisplay: 显示当前天气信息(温度、湿度、风速等)。SearchBar: 提供城市搜索功能。ForecastList: 显示未来几天天气预报。
调用天气 API
在 Vue 中通过 axios 调用天气 API,获取数据并存储到组件的 data 或 pinia/vuex 状态管理中:
import axios from 'axios';
const API_KEY = 'your_api_key';
const API_URL = `https://api.openweathermap.org/data/2.5/weather?q={city}&appid=${API_KEY}&units=metric`;
export default {
data() {
return {
weatherData: null,
error: null,
};
},
methods: {
async fetchWeather(city) {
try {
const response = await axios.get(API_URL.replace('{city}', city));
this.weatherData = response.data;
} catch (err) {
this.error = 'Failed to fetch weather data';
}
},
},
};
显示天气数据
在模板中绑定天气数据,动态展示信息:

<template>
<div v-if="weatherData">
<h3>{{ weatherData.name }}</h3>
<p>Temperature: {{ weatherData.main.temp }}°C</p>
<p>Humidity: {{ weatherData.main.humidity }}%</p>
</div>
<p v-if="error">{{ error }}</p>
</template>
添加搜索功能
在 SearchBar 组件中实现城市搜索,触发父组件的 fetchWeather 方法:
<template>
<input v-model="city" placeholder="Enter city name" />
<button @click="handleSearch">Search</button>
</template>
<script>
export default {
data() {
return {
city: '',
};
},
methods: {
handleSearch() {
this.$emit('search', this.city);
},
},
};
</script>
样式优化
使用 CSS 或 UI 库(如 TailwindCSS、Element Plus)美化界面,确保布局清晰且响应式。例如,为天气卡片添加背景和阴影效果:
.weather-card {
background: #f0f9ff;
border-radius: 8px;
padding: 16px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
部署上线
构建项目并部署到静态托管服务(如 Vercel、Netlify):
npm run build
将生成的 dist 文件夹上传到托管平台即可。






