【发布时间】:2020-09-16 05:37:02
【问题描述】:
如何正确等待获取成功,以便执行 loadMarkers() 方法不会因为 monitorsData.monitors 未定义而引发错误?
我尝试在 fetch 之前使用 await,但我也不太明白如何正确使用它。
data(){
return{
monitorsData:'',
timer:'',
loading:false,
message:'60200950',
markers: [],
}
},
created(){
this.searchStation()
this.loadMarkers()
this.timer = setInterval(this.searchStation, 50000)
},
methods:{
loadMarkers(){
for(let i = 0; i < this.monitorsData.monitors.length; i++){
this.markers.push({id: i, position: {lat: this.monitorsData.monitors[i].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[i].locationStop.geometry.coordinates[1]}})
}
},
searchStation(){
this.loading=true
var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
targetUrl = 'http://www.wienerlinien.at/ogd_realtime/monitor?DIVA='+ this.message+ '&activateTrafficInfo=stoerungkurz'
fetch(proxyUrl + targetUrl)
.then(response => response.json())
.then(jsonData => this.monitorsData = jsonData.data)
.catch(e => console.log(e))
this.loading = false
this.message = ''
},
},
另外我不知道如何在计算中防止同样的问题
computed:{
mapConfig() {
return{
...mapSettings,
zoom: 8,
center: {lat: this.monitorsData.monitors[0].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[0].locationStop.geometry.coordinates[1]}
}
}
},
【问题讨论】:
标签: javascript vue.js async-await fetch computed-properties