javascript - Vue 数据未显示在 DOM 中

标签 javascript vue.js vue-component

我正在使用 VueJS 构建一个气象站应用程序,并尝试从 OpenWeather API 添加预报数据。我可以成功提取数据并将其记录到控制台,但由于某种原因我无法在模板中显示它。

我正在获取接下来五个小时的数据并将其存储在数组中。目前我只是想展示第一个小时。这是我的代码:

<template>
  <section>
    <h1>Forecast</h1>

        <i :class="['owf owf-',iconCode[0]]"></i>
        <p>Temperature {{ currentTemp[0] }}</p>

    </div>
  </section>
</template>

<script>
  export default {
      data: function(){
        return {
          time: [],
          currentTemp: [],
          tempMin: [],
          desc: [],
          iconCode: [],
        }
      },

      methods: {
          getWeather() {
            var apiKey = "<apikey>";
            var location = "<location>";
            var units = "metric";
            var url = "http://api.openweathermap.org/data/2.5/forecast?id=" + location + "&APPID=" + apiKey + "&units=" + units;
            this.$http.get(url).then(response => {
              console.log(response.data.list);
              for(var i = 0; i < 5; i++){
                this.time[i] = response.data.list[i].dt_txt;
                this.currentTemp[i] = response.data.list[i].main.temp;
                this.tempMin[i] = response.data.list[i].main.temp_min;
                this.desc[i] = response.data.list[i].weather[0].description;
                this.iconCode[i] = response.data.list[i].weather[0].icon;
              }
            });
          },
      },

      beforeMount(){
        this.getWeather();
      },
  }
</script>

这成功地获取了我想要的数据并填充了变量(在 Vue 开发工具中验证)。模板成功注入(inject)页面,并显示静态文本。但数据不显示。给出了什么?

编辑:我应该提到我正在使用 Laravel 作为后端。我尝试在 {{ }} 前面加上 @ 符号来告诉 Blade 涉及 JS,但它只显示 @ 而不是变量。

最佳答案

在 getWeather 方法中,不能使用 array[i] = "value"。 这是因为这种对象突变没有被跟踪。

使用 array.push("value") 代替。

https://v2.vuejs.org/v2/guide/reactivity.html

问候

关于javascript - Vue 数据未显示在 DOM 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54356002/

相关文章:

vue.js - 你如何在 Vue Router 上导入具有相同名称的组件

vue.js - Vue.Draggable 能否与 Vuetify v-data-table 一起使用并允许使用表 v-slot :item. <name>?

javascript - 如何统计网站访问过程中的用户点击量,直到达到特定的点击次数?

javascript - 外部 Ajax : All at Once, 根据需要,还是其他?

vue.js - 我如何从 vuejs3 中的设置中监视函数?

javascript - vue js vue-slider-component 如何更新 Prop

javascript - 获取 Vue 组件计算实例的总数

javascript - 添加 eventListener 以模糊自定义组件上的事件?

javascript - 如何动态更改Ext js 4.0中网格的 "disableSelection"值?

Javascript 安全问题/使用 eval()