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

Vue报错:Cannot read properties of undefined (reading '0') 求助

问题描述

尝试从API动态渲染天气信息,API返回的数据可在控制台日志和页面中显示,但访问响应数组单个元素时,浏览器控制台报错“Cannot read properties of undefined (reading '0')”,页面随即停止渲染。

代码

<script>
import axios from 'axios'

export default{
  data() {
    return {
      weather: []
    };
  },
  async created(){
    try{
      const response = await axios.get('apilinkredacted');
      this.weather = response.data.daily;
      console.log(this.weather)
    } catch (error) {
      console.error(error);
    }
  }
}
</script>

<template>
  <main>
    <div v-for="n in 4" class="text-cliPurple border-t border-windowOutline pb-2 pl-2">

      <!-- weather.daily.temperature_2m_max[n-1] -->
      <p class="underline">{{ weather.time[n-1] }}</p>

    <div class="grid grid-cols-2">
      <div class="">
        <pre>
     \   /
      .-.
   ― (   ) ―
      `-’
     /   \
        </pre>
      </div>
      <div class="text-left">
        <p><span class="text-cliOrange">Temp:</span> {{ weather.temperature_2m_max[n-1] }} C</p>
        <p><span class="text-titleColor">Rain Chance:</span> {{ weather.precipitation_probability_max[n-1] }}%</p>
        <p><span class="text-userColor">Rain Amount:</span> {{ weather.rain_sum[n-1] }}mm</p>
        <p><span class="text-cliRed">UV:</span> {{ weather.uv_index_max[n-1] }}</p>

      </div>
    </div>
  </div>
  </main>
</template>

JSON响应

{
    "latitude": -35.25,
    "longitude": 149.125,
    "generationtime_ms": 0.06699562072753906,
    "utc_offset_seconds": 36000,
    "timezone": "Australia/Sydney",
    "timezone_abbreviation": "AEST",
    "elevation": 568,
    "daily_units": {
        "time": "iso8601",
        "temperature_2m_max": "°C",
        "apparent_temperature_max": "°C",
        "uv_index_max": "",
        "rain_sum": "mm",
        "precipitation_probability_max": "%"
    },
    "daily": {
        "time": [
            "2024-05-09",
            "2024-05-10",
            "2024-05-11",
            "2024-05-12",
            "2024-05-13",
            "2024-05-14",
            "2024-05-15"
        ],
        "temperature_2m_max": [
            16.5,
            14.9,
            13.1,
            13.4,
            17.5,
            15.9,
            14.7
        ],
        "apparent_temperature_max": [
            14.4,
            13.2,
            11.4,
            11.1,
            16,
            14.6,
            13.8
        ],
        "uv_index_max": [
            1.95,
            2.55,
            0.6,
            3.9,
            4.2,
            3.95,
            3.65
        ],
        "rain_sum": [
            0,
            5.1,
            26.5,
            3.7,
            0,
            0,
            0
        ],
        "precipitation_probability_max": [
            52,
            74,
            90,
            37,
            0,
            0,
            3
        ]
    }
}

补充测试情况:

  • 执行console.log(this.weather.time[0])能打印正确数据,因为该代码在API请求完成后执行,此时weather已被赋值为目标对象
  • 不指定具体数组元素时可渲染整个响应,但添加元素访问逻辑后页面空白
  • 修改请求代码为this.weather = response.data.daily.time;时,直接用weather[0]可正常显示

问题原因

初始化时weather被设为空数组,但API请求完成后赋值的是包含多个数组属性的对象。页面渲染会在API请求完成前执行,此时weather仍是空数组,访问weather.time会得到undefined,再尝试读取undefined[n-1]就会触发报错,导致页面停止渲染。


解决方案

1. 修正初始化值

将weather的初始值改为空对象,匹配后续赋值的类型:

data() {
  return {
    weather: {}
  };
}

2. 使用可选链操作符做安全访问

在模板中所有数组属性的访问前添加?.,避免访问undefined的属性:

<p class="underline">{{ weather.time?.[n-1] }}</p>
<p><span class="text-cliOrange">Temp:</span> {{ weather.temperature_2m_max?.[n-1] }} C</p>
<p><span class="text-titleColor">Rain Chance:</span> {{ weather.precipitation_probability_max?.[n-1] }}%</p>
<p><span class="text-userColor">Rain Amount:</span> {{ weather.rain_sum?.[n-1] }}mm</p>
<p><span class="text-cliRed">UV:</span> {{ weather.uv_index_max?.[n-1] }}</p>

3. 条件渲染确保数据加载完成

给外层main标签添加v-if判断,只有当weather.time存在时才渲染内容:

<main v-if="weather.time">
  <!-- 原模板内容 -->
</main>

内容的提问来源于stack exchange,提问作者Rhys Swansbra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 15:03:09