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

VueJs渲染报错:TypeError: Cannot read property 'data' of undefined求助

Fixing "Cannot read property 'data' of undefined" in Vue.js Render

That error pops up because when Vue first renders your template, the hasil variable is still undefined—your API request is asynchronous, so the data hasn't arrived yet. When the template tries to access hasil.data.data, it's trying to get a property from something that doesn't exist yet. Here are a few straightforward fixes:

1. Initialize hasil with a default structure

In your component's data, set an initial value for hasil that matches the structure of your API response. This way, even before the API call finishes, Vue has something to work with:

export default {
  data() {
    return {
      hasil: {
        data: {
          data: [] // Empty array so v-for has something to iterate over
        }
      }
    }
  },
  // ... your API fetch logic here
}

2. Use conditional rendering with v-if

Wrap your v-for section in a container that only renders when hasil.data.data exists. This prevents Vue from trying to access properties of undefined:

<template>
  <div>
    <!-- Only render when the data is available -->
    <div v-if="hasil && hasil.data && hasil.data.data">
      <div v-for="h in hasil.data.data" :key="h.id">
        <div class="card blue-grey darken-1 left-align">
          <div class="card-content white-text">
            <span class="card-title">Title: {{ h.title }} | ID: {{ h.id }}</span>
            <p>Body: {{ h.body }}</p>
          </div>
          <div class="card-action">
            <!-- Your link here -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

3. Use optional chaining (ES2020+)

If your project supports modern JavaScript, you can use the optional chaining operator (?.) to safely access nested properties. This will return undefined instead of throwing an error if any parent property is missing:

<template>
  <div>
    <div v-for="h in hasil?.data?.data" :key="h?.id">
      <div class="card blue-grey darken-1 left-align">
        <div class="card-content white-text">
          <span class="card-title">Title: {{ h.title }} | ID: {{ h.id }}</span>
          <p>Body: {{ h.body }}</p>
        </div>
        <div class="card-action">
          <!-- Your link here -->
        </div>
      </div>
    </div>
  </div>
</template>

Any of these approaches should fix the error. The first one is great because it sets a clear default state, while the optional chaining is more concise if you're using newer JS features.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:54:47