【问题标题】:How to modify nested JSON data with Vue and Vue Resource如何使用 Vue 和 Vue Resource 修改嵌套的 JSON 数据
【发布时间】:2018-07-31 11:58:22
【问题描述】:

使用 OpenWeatherMap API 在 Vue 中处理一些非常简单的事情。

可以正确渲染所有数据,但我想修改这些数据,但不确定实现该目标的最佳方法是什么。

这是我的代码:

index.pug

section#weather
  ul
    li(v-for='forecast in forecasts')
      p.time Time: {{ times }}
      p.temperature Temperature: {{ temperatures }}º
      p.description Description: {{ forecast.weather[0].description }}
      img.icon(v-bind:src="'https://openweathermap.org/img/w/' + forecast.weather[0].icon + '.png'")

script.js

var weather = new Vue({
el: '#weather',

data: {
    forecasts: [],
    temperatures: [],
    times: []
},

created: function () {
    this.fetchData();
},        

methods: {
    fetchData: function () {
                     this.$http.get('http://api.openweathermap.org/data/2.5/forecast?q=london&units=metric&appid=YOURAPIKEY')
        .then(response => {
            this.forecasts = response.data.list;
            this.temperatures = Math.round(response.data.list[0].main.temp);
            this.times = moment.unix(response.data.list[0].dt);
        })
    }
}
});

这将只渲染第一次和温度,但正确的各种描述和图标。

例如将 index.pug 中的内容更改为 p.time Time: {{ forecast.dt }} 可以正常工作,但随后无法修改时间格式。

有关 OpenWeatherMap JSON 格式的更多信息:https://openweathermap.org/forecast5

【问题讨论】:

  • 您是否仔细检查了您在 list[0].dt 和 list[0].main.temp 中获得的数据?
  • @NickM 是的,我得到的数据是来自 JSON 文件的第一次时间和温度,但我需要渲染所有时间和温度,就像我为描述和图标所做的那样。

标签: json api vue.js vue-resource openweathermap


【解决方案1】:

在解析数据(并将其设置为 this.temperaturesthis.times)时,您不应该对 0 索引进行硬编码。相反,由于forecast 在循环的任何循环中都与forecasts[i] 相同,请执行以下操作:

section#weather
  ul
    li(v-for='forecast in forecasts')
      p.time Time: {{ forecast.dt}}
      p.temperature Temperature: {{ Math.round(forecast.main.temp) }}º
      p.description Description: {{ forecast.weather[0].description }}
      img.icon(v-bind:src="'https://openweathermap.org/img/w/' + forecast.weather[0].icon + '.png'")

您的fetchData() 变得简单:

fetchData: function () {                    
  this.$http.get('http://api.openweathermap.org/data/2.5/forecast?q=london&units=metric&appid=YOURAPIKEY')
    .then(response => this.forecasts = response.data.list)
}

【讨论】:

  • 谢谢!不知道为什么我没有考虑修改 pug 模板中的数据...
  • 很高兴能帮上忙!
猜你喜欢
  • 2016-06-08
  • 2022-01-25
  • 2016-11-15
  • 2019-01-24
  • 2017-04-09
  • 2021-01-27
  • 2021-11-10
  • 2021-03-01
  • 2017-07-22
相关资源
最近更新 更多