为什么在此v​​ue.js示例中获得未定义的属性

时间:2019-07-01 17:57:14

标签: javascript vue.js

我的Vue开发工具和单元测试充斥着:

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

在看了其他文章之后,我猜该错误的原因与使用胖箭头功能有关?那是我唯一能想到的。奇怪的是,尽管有所有这些错误,但实际组件本身在预期的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>

无法读取未定义的属性“ time_start”

1 个答案:

答案 0 :(得分:0)

您正在发送异步请求,并且模板依赖于此信息已存在。该组件“看起来不错”,但是一瞬间它没有任何真实的数据要呈现(job_execs在尝试呈现时仍在等待数据)。

您可以通过在标签中添加v-if语句来解决此问题,

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

希望这会有所帮助:-)