我无法从开放的天气API中得到结果,我得到了这个错误:无法读取未定义的属性(读取“天气”),但是当我将v列表部分移到另一个页面时,错误就消失了。
代码如下,如有任何帮助,将不胜感激:
<template>
<div>
<v-row>
<v-col sm="10" offset-sm="1" lg="8" offset-lg="2">
<h2 class="text-uppercase title text-center my-5">weather forecast</h2>
<v-row justify="center">
<v-btn color="primary" outlined class="mt-7" @click="showWeatherInfo">Show Info</v-btn>
</v-row>
<v-row>
<v-list>
<v-list-item-group>
<v-list-item>Weather: {{item.weather[0].main}}</v-list-item>
<v-list-item> temperature: {{item.main.temp}} ° C. </v-list-item>
<v-list-item> humidity: {{item.main.humidity}} % </v-list-item>
<v-list-item> wind: {{item.wind.speed}}m </v-list-item>
</v-list-item-group>
</v-list>
</v-row>
<v-row justify="center">
<v-btn color="primary" outlined class="mt-7">Go Back</v-btn>
</v-row>
</v-col>
</v-row>
</div>
</template>
<script>
export default{
data(){
return{
}
},
methods : {
async showWeatherInfo(){
const item = await this.$axios.$get(`https://api.openweathermap.org/data/2.5/weather?q=tehran&appid=${process.env.apiKey}`)
console.log(item)
return { item }
}
}
}
</script>
发布于 2021-11-08 15:07:39
您应该使用最佳实践来使用AXIOS调用API,并且应该在Vue.js中观察到有两点可以解决您的问题:
1-您需要定义像item:[]这样的数据对象或数组,并在您称为showWeatherInfo()的函数中用this.item分配您的响应
2-您需要在挂载生命周期中调用您的函数。
<template>
<div>
<v-row>
<v-col sm="10" offset-sm="1" lg="8" offset-lg="2">
<h2 class="text-uppercase title text-center my-5">weather forecast</h2>
<v-row justify="center">
<v-btn color="primary" outlined class="mt-7" @click="showWeatherInfo">Show Info</v-btn>
</v-row>
<v-row>
<v-list>
<v-list-item-group v-if="item">
<v-list-item>Weather: {{item.weather[0].main}}</v-list-item>
<v-list-item> temperature: {{item.main.temp}} ° C. </v-list-item>
<v-list-item> humidity: {{item.main.humidity}} % </v-list-item>
<v-list-item> wind: {{item.wind.speed}}m </v-list-item>
</v-list-item-group>
</v-list>
</v-row>
<v-row justify="center">
<v-btn color="primary" outlined class="mt-7">Go Back</v-btn>
</v-row>
</v-col>
</v-row>
</div>
</template>
<script>
export default{
data(){
return{
item:[]
}
},
methods : {
async showWeatherInfo(){
const response = await this.$axios.$get(`https://api.openweathermap.org/data/2.5/weather?q=tehran&appid=${process.env.apiKey}`)
this.item = response
}
}
}
</script>发布于 2021-11-03 14:21:12
你也许可以用这个来解决你的问题
<v-list-item-group v-if="item">原因是,如果尝试在对象为空时迭代它,就会得到一个错误。
同时,您的template是同步的,所以您只需要告诉它,有些东西可能是空的,它不需要害怕。
https://stackoverflow.com/questions/69825528
复制相似问题