首页 > 解决方案 > 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,尽管新数据被成功获取。

确保在成功获取后正确呈现新数据的最佳步骤是什么?

-香港

标签: vue.jsfetchrender

解决方案


在渲染天气数据的组件(或任何容器)中,添加一个键(如 :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;
    },

您可以强制重新渲染。


推荐阅读