首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >API更新后列表中的重复项

API更新后列表中的重复项
EN

Stack Overflow用户
提问于 2019-08-27 17:46:07
回答 1查看 240关注 0票数 1

我正在学习vuejs,我正在做一个天气应用程序,目标是用指数(humidex)对城市进行排名。我通过API (axios)获取天气信息,以便从几个城市收集数据。我想每隔x分钟自动更新一次数据,问题是:我的一些结果是重复的(新的数据不能替换旧的)。

我试图为每个项目设置一个唯一的键(基于纬度和经度),它适用于多个结果,但不适用于所有结果。

代码语言:javascript
复制
  data () {
    return {
      items:[],
      show: false,
      cities: cities,
      newCity:''
    } 
  },
  components: {
    Item
  },
  computed: {
    sortHumidex() {
      return this.items.slice().sort((a,b) => {
        return this.getHumidex(b) - this.getHumidex(a) || b.current.temp_c - a.current.temp_c
      })
    }
  },
  methods: {
    addCity() {
      if (this.newCity.trim().length == 0) {
        return
      }
      this.cities.push(this.newCity)
      this.newCity = ''
    },
    getHumidex: (el) => {
      const e = 6.112 * Math.pow(10,(7.5*el.current.temp_c/(237.7+el.current.temp_c)))
      *(el.current.humidity/100)
      return Math.round(el.current.temp_c + 5/9 * (e-10))
    },
    indexGeo: (e) => {
      const lat = Math.round(Math.abs(e.location.lat))
      const lon = Math.round(Math.abs(e.location.lon))
      return lat.toString() + lon.toString()
    },

    getApi: function () {
      const promises = [];

      this.cities.forEach(function(element){
        const myUrl = apiUrl+element;
        promises.push(axios.get(myUrl))
      });
      let self = this;

      axios
        .all(promises)
        .then(axios.spread((...responses) => {
          responses.forEach(res => self.items.push(res.data))
      }))
        .catch(error => console.log(error));
    }
  },
  created() {
    this.getApi()
    this.show = true
  }
}

更新API时的呈现:

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-27 20:22:38

通过推送到现有的项目数组,您必须处理重复的可能性。这可以通过每次调用API时替换 items来消除。

取代:

代码语言:javascript
复制
responses.forEach(res => self.items.push(res.data))

通过以下方式:

代码语言:javascript
复制
self.items = responses.map(res => res.data)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57679834

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档