vue实现天气查询
实现天气查询功能
使用Vue实现天气查询功能需要调用天气API获取数据,并将结果展示在页面上。以下是具体实现方法:
注册天气API服务
推荐使用高德地图天气API、和风天气API或OpenWeatherMap等免费服务。注册账号后获取API密钥,用于后续请求授权。
例如高德天气API的注册地址为:https://lbs.amap.com/api/javascript-api/guide/services/weather
安装axios发送请求
在Vue项目中安装axios库处理HTTP请求:
npm install axios
创建天气查询组件
新建Weather.vue组件文件,包含查询输入框和结果显示区域:
<template>
<div>
<input v-model="city" placeholder="输入城市名称"/>
<button @click="getWeather">查询</button>
<div v-if="weatherData">
<h3>{{ weatherData.city }}天气</h3>
<p>温度:{{ weatherData.temperature }}℃</p>
<p>天气:{{ weatherData.weather }}</p>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
city: '',
weatherData: null
}
},
methods: {
async getWeather() {
try {
const response = await axios.get(
`https://restapi.amap.com/v3/weather/weatherInfo?key=你的API密钥&city=${this.city}`
);
this.weatherData = {
city: response.data.lives[0].city,
temperature: response.data.lives[0].temperature,
weather: response.data.lives[0].weather
};
} catch (error) {
console.error('获取天气失败:', error);
}
}
}
}
</script>
处理API响应数据
根据不同的天气API返回格式,调整数据处理逻辑。高德API返回的天气数据格式为:
{
"lives": [
{
"city": "北京市",
"weather": "晴",
"temperature": "23"
}
]
}
添加样式美化界面
为组件添加CSS样式提升用户体验:
<style scoped>
input {
padding: 8px;
margin-right: 10px;
}
button {
padding: 8px 16px;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
}
</style>
错误处理和加载状态
添加加载状态和错误提示提升交互体验:
<template>
<div>
<input v-model="city" placeholder="输入城市名称"/>
<button @click="getWeather" :disabled="loading">
{{ loading ? '查询中...' : '查询' }}
</button>
<div v-if="error" class="error">{{ error }}</div>
<div v-if="weatherData">
<!-- 天气信息展示 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
loading: false,
error: ''
}
},
methods: {
async getWeather() {
this.loading = true;
this.error = '';
try {
// 请求代码
} catch (error) {
this.error = '获取天气信息失败,请重试';
} finally {
this.loading = false;
}
}
}
}
</script>
<style>
.error {
color: red;
margin-top: 10px;
}
</style>
部署注意事项
- 将API密钥存储在环境变量中而非代码里
- 考虑添加防抖功能减少API请求次数
- 对于生产环境,建议通过后端服务代理天气API请求
以上实现方案可以扩展添加更多天气细节如湿度、风速等,或增加天气预报功能显示未来几天天气情况。







