我正在使用 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/