vue.js - Vue.js 通过 API 调用渲染新数据
问题描述
我正在制作一个用 Vue.js 编写的天气应用程序,它会定期获取天气数据,但是在初始 API 调用后呈现新数据时遇到问题。
在 data 中声明了空数据数组,并使用了一个计时器来获取新数据,如下所示:
data() {
return {
weatherData: [],
timer: '',
};
},
我已经在方法中声明了数据获取,如下所示:
methods: {
async fetchWeatherData() {
const response = await fetch("http://localhost:5002/timeseries");
const data = await response.json();
if (response.ok) {
console.log("Data fetched sucssefully!");
}
return data;
},
当应用程序加载时,将启动 fetchWeatherData 和 setInterval:
async created() {
this.weatherData = await this.fetchWeatherData();
setInterval(() => this.timer = this.fetchWeatherData(), 10000)
},
问题是新数据没有被渲染到 DOM,尽管新数据被成功获取。
确保在成功获取后正确呈现新数据的最佳步骤是什么?
-香港
解决方案
在渲染天气数据的组件(或任何容器)中,添加一个键(如 :key="renderWeatherKey")。将 renderWeatherKey 添加到组件数据。
data() {
return {
weatherData: [],
timer: '',
renderWeatherKey: 0
};
},
在 fetchWeatherData() 方法中,在 'if' 条件内,添加 this.renderWeatherKey++ :
async fetchWeatherData() {
const response = await fetch("http://localhost:5002/timeseries");
const data = await response.json();
if (response.ok) {
console.log("Data fetched sucssefully!");
this.renderWeatherKey++
}
return data;
},
您可以强制重新渲染。
推荐阅读
- c# - System.IO.FileNotFoundException: '无法加载文件或程序集
- javascript - 如何循环遍历元素及其子元素以添加或删除类 - Javascript/jQuery
- dart - 通过 Bloc 模式管理多个小部件的状态
- javascript - Javascript date-fns 更具体的 distanceInWords
- matlab - 是否可以将音频从 matlab 发送到 unity?我得到错误太多的输出争论
- sql-server - 将 SSRS 参数作为参数传递给 Query
- c# - 将 ASP.NET 控件动态添加到网页
- sql - 在 Transact-SQL 中计算两个值的最大值
- spring - 我得到文件不存在异常
- postgresql - 使用 postgres-simple 定义 FromRow 实例时出错