You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NuxtJS调用OpenWeather API报错Cannot read properties of undefined (reading 'weather')

问题原因
  • 你没有在data中声明item为响应式变量,showWeatherInfo方法里return的item无法被模板读取,页面初始渲染时item为undefined,直接读取item.weather自然会抛出错误
  • 接口仅在点击按钮后才会触发调用,页面刚加载时没有任何数据赋值给item,模板直接访问嵌套属性必然报错
  • 把v-list移到其他页面就不报错,大概率是其他页面默认没有直接渲染这段依赖item的代码,或者其他页面提前声明了对应变量、加了渲染判断
修复方案
  1. 在data中声明响应式变量item,默认值设为null
  2. 接口请求成功后直接把返回值赋值给this.item,不需要return
  3. 给v-list添加v-if="item"判断,只有item有值时才渲染列表内容,避免初始渲染报错
修改后的完整代码
<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-if判断,有数据才渲染 -->
          <v-list v-if="item">
            <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{
      // 声明响应式变量item
      item: null
    }
  },
  methods : {
    async showWeatherInfo(){
      const res = await this.$axios.$get(`https://api.openweathermap.org/data/2.5/weather?q=tehran&appid=${process.env.apiKey}`)
      console.log(res)
      // 直接赋值给响应式变量
      this.item = res
    }
  }
}
</script>

内容的提问来源于stack exchange,提问作者elham zeinodini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 19:27:03