Vue+Axios调用OpenWeather API问题:回车后城市重置为默认值
问题解决方法
核心问题分析
- 回车触发表单默认提交:输入框放在
<form>标签内,按下回车会触发表单默认提交行为,导致页面刷新,组件重新初始化,city自然变回初始值seoul。 updated钩子滥用:每次组件数据更新都会调用weatherData,不仅产生重复请求,还可能引发不必要的循环更新。
具体修复步骤
- 阻止表单默认提交:给
<form>添加@submit.prevent,避免页面刷新。 - 移除
updated钩子:仅在mounted初始化时调用一次查询,后续只在用户主动触发(回车、点击按钮)时调用weatherData。 - 明确查询触发时机:给输入框绑定回车事件,手动触发查询逻辑。
修改后的完整代码
<template> <div id="container"> <h1>Todays Reports</h1> <img :src="icon" alt="" /> <h2> <span>{{ city }}</span> 's weather <br /> <b> {{ dsc }}</b> </h2> <p>temp: {{ temp }}<span>°</span></p> <!-- 阻止表单默认提交行为 --> <form @submit.prevent="weatherData"> <h3> <span> 도시</span>를 입력하세요 </h3> <!-- 绑定回车事件触发查询 --> <input type="text" v-model="city" @keyup.enter="weatherData" /> <!-- 可取消注释按钮,作为额外触发方式 --> <!-- <button @click="weatherData">확인</button> --> </form> </div> </template> <script> import axios from "axios"; import background from "@/assets/background"; export default { data() { return { bg: background, icon: "", dsc: "", temp: "", city: "seoul", mainDsc: '' }; }, mounted() { this.weatherData(); }, // 移除updated钩子,避免重复请求和循环更新 methods: { weatherData() { // 过滤空输入,避免无效请求 if (!this.city.trim()) return; axios .get( `https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=209427778b168dd3cfb8c77b931a8344&units=metric` ) .then((response) => { let data = response.data; console.log(this.city) this.dsc = data.weather[0].main; this.mainDsc = data.weather[0].main this.temp = data.main.temp; this.icon = `https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`; const container = document.querySelector('#container') for (let i = 0; i < this.bg.length; i++) { if (this.mainDsc == this.bg[i].main) { container.style.background = this.bg[i].background } } }) .catch((error) => { console.log(error); }); }, }, }; </script>
额外优化建议
- 给
weatherData添加防抖处理,避免用户快速输入时频繁发送请求。 - 增加查询失败的提示逻辑(比如城市不存在时,给用户显示错误信息)。
内容的提问来源于stack exchange,提问作者jsol lee
相关产品推荐
相关产品推荐

