vue实现天气小案例
Vue实现天气小案例
创建Vue项目
使用Vue CLI创建一个新项目,确保已安装Node.js和npm。
vue create weather-app
cd weather-app
npm install axios
获取天气API
注册并获取免费的天气API密钥,例如使用OpenWeatherMap或和风天气。以下以OpenWeatherMap为例:
const API_KEY = 'your_api_key';
const API_URL = `https://api.openweathermap.org/data/2.5/weather?q={city}&appid=${API_KEY}&units=metric`;
创建天气组件
在src/components下创建Weather.vue文件,包含模板、脚本和样式。
<template>
<div class="weather">
<input v-model="city" placeholder="输入城市名称" @keyup.enter="fetchWeather" />
<div v-if="weatherData">
<h2>{{ weatherData.name }}</h2>
<p>温度: {{ weatherData.main.temp }}°C</p>
<p>天气: {{ weatherData.weather[0].description }}</p>
<img :src="`https://openweathermap.org/img/wn/${weatherData.weather[0].icon}@2x.png`" />
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
city: '',
weatherData: null
};
},
methods: {
fetchWeather() {
axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=${API_KEY}&units=metric`)
.then(response => {
this.weatherData = response.data;
})
.catch(error => {
console.error('获取天气数据失败:', error);
});
}
}
};
</script>
<style>
.weather {
text-align: center;
margin-top: 20px;
}
input {
padding: 8px;
margin-bottom: 10px;
}
</style>
在主组件中引入
在App.vue中引入并使用Weather组件。
<template>
<div id="app">
<Weather />
</div>
</template>
<script>
import Weather from './components/Weather.vue';
export default {
components: {
Weather
}
};
</script>
运行项目
启动开发服务器,查看效果。
npm run serve
注意事项
- 确保替换
your_api_key为实际的API密钥。 - 处理网络请求错误,提供用户友好的提示。
- 如果需要更复杂的UI,可以添加加载状态或更多天气信息字段。







