Vue.js 呈现来自 API 调用的新数据

Vue.js render new data from API call

我正在制作一个用 Vue.js 编写的天气应用程序,它会定期获取天气数据,但在初始 API 调用后呈现新数据时出现问题。

数据中声明了空数据数组,并使用定时器获取新数据,如:

      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;
    },

您可以强制重新渲染。

解决方案,由 James Thomson over at the Vue forum, was to set the setInterval to async, since the fetch method also is async. See the full answer here 发布。