Vue.js定时调用API拉取天气数据后新数据无法渲染问题咨询
问题根因
你的定时任务逻辑只执行了接口请求,没有把新拿到的数据赋值给响应式变量weatherData,自然不会触发DOM更新。除此之外你的定时器变量使用方式也有问题:setInterval的返回值是定时器ID,用来后续清理定时器用的,你现在把接口请求返回的Promise赋值给了timer,后续无法正常销毁定时任务。
修正方案
调整定时任务的回调逻辑,请求成功后把新数据赋值给this.weatherData,同时正确存储定时器ID:
第一步:调整created钩子逻辑
async created() { // 首次请求赋值 this.weatherData = await this.fetchWeatherData(); // 存储定时器ID,方便beforeDestroy阶段清理 this.timer = setInterval(async () => { // 定时请求后把新数据赋值给响应式变量 this.weatherData = await this.fetchWeatherData(); }, 10000) },
第二步:补充定时器清理逻辑,避免内存泄漏
beforeDestroy() { // 组件销毁时清除定时任务 clearInterval(this.timer) }
可选优化:增加接口异常处理,避免静默失败
可以给fetchWeatherData补充异常捕获逻辑,网络出错时可以给用户提示:
async fetchWeatherData() { try { const response = await fetch("http://localhost:5002/timeseries"); const data = await response.json(); if (response.ok) { console.log("Data fetched successfully!"); return data; } throw new Error('接口请求异常') } catch (err) { console.error('拉取天气数据失败:', err) // 异常时可以保留旧数据,也可以根据业务需求赋值为空 return this.weatherData } },
内容的提问来源于stack exchange,提问作者Hans-Kristian Norum Eidesen
相关产品推荐
相关产品推荐

