vue实现天气界面
实现天气界面的核心步骤
安装依赖与项目初始化
使用Vue CLI或Vite创建项目,安装axios用于API请求。如使用npm:npm install axios
获取天气API密钥 注册开放天气API服务(如OpenWeatherMap),获取免费API密钥。注意免费版可能有调用频率限制。
创建基础组件结构
<template>
<div class="weather-app">
<div class="search-box">
<input
type="text"
v-model="city"
@keyup.enter="fetchWeather"
placeholder="输入城市名称"
/>
</div>
<div class="weather-wrap" v-if="weatherData">
<!-- 天气信息展示区 -->
</div>
</div>
</template>
数据获取与处理
设置响应式数据
data() {
return {
city: '',
weatherData: null,
apiKey: 'YOUR_API_KEY',
error: null
}
}
实现天气获取方法

methods: {
async fetchWeather() {
try {
const response = await axios.get(
`https://api.openweathermap.org/data/2.5/weather?q=${this.city}&units=metric&appid=${this.apiKey}`
)
this.weatherData = response.data
this.error = null
} catch (err) {
this.error = '城市未找到,请重试'
this.weatherData = null
}
}
}
界面展示优化
主要天气信息展示
<div class="weather-box">
<div class="temp">{{ Math.round(weatherData.main.temp) }}°C</div>
<div class="weather">{{ weatherData.weather[0].description }}</div>
</div>
添加天气图标 使用API返回的图标代码动态显示:
<img
:src="`https://openweathermap.org/img/wn/${weatherData.weather[0].icon}@2x.png`"
alt="Weather icon"
/>
补充天气详情

<div class="details">
<div class="humidity">
<span>湿度</span>
{{ weatherData.main.humidity }}%
</div>
<div class="wind">
<span>风速</span>
{{ weatherData.wind.speed }} km/h
</div>
</div>
样式设计与交互增强
基础样式示例
.weather-app {
max-width: 500px;
margin: 0 auto;
padding: 20px;
}
.search-box input {
width: 100%;
padding: 10px;
font-size: 16px;
}
.weather-wrap {
margin-top: 20px;
background: rgba(255,255,255,0.2);
padding: 20px;
border-radius: 10px;
}
.temp {
font-size: 4rem;
font-weight: bold;
}
添加加载状态 在data中添加loading状态,请求时设为true,完成后设为false,配合v-if显示加载动画。
位置自动检测 可使用浏览器Geolocation API获取用户位置,然后反向查询城市名称:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
this.fetchWeatherByCoords(position.coords.latitude, position.coords.longitude)
})
}
实现天气背景变化 根据天气状况动态改变背景:
computed: {
weatherClass() {
if (!this.weatherData) return ''
const main = this.weatherData.weather[0].main.toLowerCase()
return `weather-${main}`
}
}
对应CSS定义不同天气的背景样式。





