天气案例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<input type="button" value='去百度 获取天气预报'>
	<table id='weather'></table>
</body>
</html>

<script type="text/javascript" src='../js/template-native.js'></script>

<script type="text/template" id='template'>
	<%for(var i=0;i<weather_data.length;i++) {%>
		<tr>
			<td><%=weather_data[i].date%></td>
			<td><img src="<%=weather_data[i].dayPictureUrl%>" alt=""></td>
			<td><img src="<%=weather_data[i].nightPictureUrl%>" alt=""></td>
			<td><%=weather_data[i].temperature%></td>
			<td><%=weather_data[i].weather%></td>
			<td><%=weather_data[i].wind%></td>
		</tr>
	<% } %>
</script>

<script type="text/javascript" src='../js/jquery.min.js'></script>
<script type="text/javascript">
	$("input").click(function () {
		$.ajax({
			url:"http://api.map.baidu.com/telematics/v3/weather?location=上海&output=json&ak=tq0Kt0NFYheTCj5mszast0drkIqqVTNn",
			dataType:'jsonP',
			success:function(data){
				// 读取对象
				var weatherResults = data.results[0];

				// 读取模板
				var str = template('template',weatherResults);
				console.log(str);
				
				// 添加到界面上
				$("#weather").append(str);
			}
		})
	})
</script>


演示效果:


用到百度开发者工具:http://lbsyun.baidu.com/index.php?title=car/api/weather

<think>好的,我需要回答用户关于使用Vue和axios实现天气应用的案例或教程的请求。首先,我应该根据用户提供的引用内容来构建回答,特别是引用[1]和引用[2]提到的内容。用户需要示例代码和教程步骤,所以需要分步骤讲解。 首先,用户可能已经安装了Vue,但需要确认环境设置,包括创建Vue项目、安装axios和vue-axios。然后,配置axios的实例,设置基础URL和API密钥。这部分需要确保代码正确,比如在src目录下创建axios实例文件。 接下来是创建Weather.vue组件。用户需要输入城市名称,点击按钮触发获取天气的函数。这里需要处理输入框的v-model绑定,以及按钮的点击事件。然后,在methods里定义fetchWeather方法,使用axios.get发送请求到API,并处理响应数据。同时,错误处理也是必要的,用try-catch块捕获可能的错误。 数据展示部分,需要在模板中设计显示天气信息的结构,比如温度、天气状况、湿度等,使用v-if来控制显示条件,确保数据存在时才渲染。样式部分可以添加一些简单的CSS来美化界面,但用户可能更关注功能实现,所以样式可以保持简洁。 最后,需要提醒用户替换API密钥,并可能推荐一些免费的天气API提供商,如OpenWeatherMap。同时,注意事项比如跨域问题可能需要配置代理,但引用中没有提到,所以可以简要提及。另外,API调用次数限制也是需要注意的。 确保所有步骤清晰,代码示例正确,并且符合用户的要求。检查是否遗漏了关键点,比如安装依赖、配置axios、组件结构、数据绑定、方法实现和错误处理。还要确保使用中文回答,行内公式用$...$,独立公式用$$...$$,但这个问题可能不涉及数学公式,所以可能不需要。不过要遵循系统级指令中的其他要求,比如引用标识,在回答末尾添加相关问题,并保持结构清晰。</think>以下是如何使用Vue和axios实现天气预报应用的详细步骤与代码示例: ### 一、环境准备 1. 创建Vue项目 ```bash vue create weather-app ``` 2. 安装axios和vue-axios ```bash npm install axios vue-axios ``` ### 二、核心代码实现 ```vue <!-- src/components/Weather.vue --> <template> <div class="weather-container"> <h2>天气预报查询</h2> <div class="input-group"> <input type="text" v-model="city" placeholder="输入城市名称" @keyup.enter="fetchWeather" > <button @click="fetchWeather">查询</button> </div> <div v-if="weatherData" class="weather-info"> <h3>{{ weatherData.name }}</h3> <p>温度:{{ Math.round(weatherData.main.temp) }}°C</p> <p>天气:{{ weatherData.weather[0].description }}</p> <p>湿度:{{ weatherData.main.humidity }}%</p> </div> <div v-if="error" class="error"> {{ error }} </div> </div> </template> <script> import axios from 'axios' export default { data() { return { city: '', weatherData: null, 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=YOUR_API_KEY` ) this.weatherData = response.data this.error = null } catch (err) { this.error = '无法获取天气数据,请检查城市名称或网络连接' this.weatherData = null } } } } </script> <style scoped> .weather-container { max-width: 600px; margin: 2rem auto; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); } .input-group { margin: 20px 0; display: flex; gap: 10px; } input { flex: 1; padding: 8px; border: 1px solid #ccc; } button { padding: 8px 16px; background: #42b983; color: white; border: none; cursor: pointer; } .error { color: #ff4444; margin-top: 10px; } </style> ``` ### 三、关键配置说明 1. **API密钥获取**: - 到[OpenWeatherMap](https://openweathermap.org/)注册获取免费API密钥 - 替换代码中的`YOUR_API_KEY` 2. **axios特性应用**: - 使用`async/await`处理异步请求 - 错误处理包含网络错误和API返回错误 - 温度数据通过`Math.round()`进行四舍五入处理 ### 四、最佳实践建议 1. 推荐将axios实例封装为独立模块(在`src/utils/axios.js`): ```javascript import axios from 'axios' export default axios.create({ baseURL: 'https://api.openweathermap.org/data/2.5', params: { appid: 'YOUR_API_KEY', units: 'metric' } }) ``` 2. 重要安全提示: - 前端API密钥应通过环境变量管理 - 生产环境建议通过后端代理转发请求 ### 五、相关扩展功能 1. 可添加的功能扩展: - 天气预报图标显示 - 未来24小时温度变化折线图 - 空气质量指数显示 - 城市自动补全功能
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值