why am I getting property of undefined in this vue

2019-08-11 19:15发布

This question already has an answer here:

My vue dev tools and unittests are being flooded with:

Error in render: "TypeError: Cannot read property 'time_start' of undefined"
Cannot read property 'time_start' of undefined

After looking at some other posts, I'm guessing the reason for this error is related to the use of the fat arrow function? That's the only thing I can come up with. What's strange is that despite all these errors, the actual component itself renders fine with the expected time_start.

  created() {
    this.JobExecEndpoint =
      process.env.VUE_APP_TEST_URL +
      "/api/v2/tool=" +
      this.$route.params.tool +
      "&job=" +
      this.$route.params.job +
      "&id=" +
      this.$route.params.id;
    fetch(this.JobExecEndpoint)
      .then(response => response.json())
      .then(body => {
        this.cleanStartTime = moment(body[0].time_start);
        this.cleanEndTime = moment(body[0].time_end);
        this.cleanDuration = this.calculateDuration(
          this.cleanStartTime,
          this.cleanEndTime
        );
        this.job_execs.push({
          name: body[0].job.name,
          build_id: body[0].id,
          env: body[0].job.env,
          time_start: this.cleanStartTime.format("LLL"),
          time_end: this.cleanEndTime.format("LLL"),
          duration: this.cleanDuration,
          status: body[0].status.name,
          job: body[0].job,
        });
      })
      .catch(err => {
        console.log("Error Fetching:", this.JobExecEndpoint, err);
        return { failure: this.JobExecEndpoint, reason: err };
      });
  }


<template>
  <div class="overview">
    <h3>Overview</h3>
    <table :style="overviewStyle">
      <tr>
        <td :style="tdStyle">Start Time</td>
        <td :style="tdStyle">{{ job_execs[0].time_start }}</td>
      </tr>
      <tr>
    </table>
</template>

Cannot read property 'time_start' of undefined

1条回答
Anthone
2楼-- · 2019-08-11 19:53

You're sending off an asynchronous request and the template is relying on this information to already exist. The component "looks fine" but for a split second it didn't have any real data to render (job_execs was still waiting for data when this attempted to render).

You can fix this by adding in a v-if statement to your tag like so:

<td v-if:"job_execs" :style="tdStyle">{{ job_execs[0].time_start }}</td>

Hope this helps :-)

查看更多
登录 后发表回答