如何使用Vue和Vue Resource修改嵌套的JSON数据

时间:2018-02-21 01:26:03

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

使用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);
        })
    }
}
});

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

Changin在 index.pug p.time Time: {{ forecast.dt }}的内容工作正常但无法修改时间格式。

有关如何在此处格式化OpenWeatherMap JSON的更多信息:https://openweathermap.org/forecast5

1 个答案:

答案 0 :(得分:0)

解析数据时,不应对0索引进行硬编码(并将其设置为this.temperaturesthis.times)。相反,由于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)
}