我正在学习vuejs,我正在做一个天气应用程序,目标是用指数(humidex)对城市进行排名。我通过API (axios)获取天气信息,以便从几个城市收集数据。我想每隔x分钟自动更新一次数据,问题是:我的一些结果是重复的(新的数据不能替换旧的)。
我试图为每个项目设置一个唯一的键(基于纬度和经度),它适用于多个结果,但不适用于所有结果。
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时的呈现:

发布于 2019-08-27 20:22:38
通过推送到现有的项目数组,您必须处理重复的可能性。这可以通过每次调用API时替换 items来消除。
取代:
responses.forEach(res => self.items.push(res.data))通过以下方式:
self.items = responses.map(res => res.data)https://stackoverflow.com/questions/57679834
复制相似问题