为什么我在这个 vue.js 示例中得到 undefined 的属性 [英] why am I getting property of undefined in this vue.js example
问题描述
我的 vue 开发工具和单元测试充斥着:
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
看了一些其他的帖子后,我猜测这个错误的原因与使用粗箭头功能有关?这是我唯一能想到的.奇怪的是,尽管存在所有这些错误,实际组件本身在预期的 time_start 下呈现良好.
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>
无法读取未定义的属性time_start"
Cannot read property 'time_start' of undefined
推荐答案
您正在发送一个异步请求,而模板依赖于该信息已经存在.该组件看起来不错",但有一瞬间它没有任何真实的数据要渲染(job_execs 在尝试渲染时仍在等待数据).
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).
您可以通过在标签中添加 v-if 语句来解决此问题,如下所示:
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>
希望这有帮助:-)
这篇关于为什么我在这个 vue.js 示例中得到 undefined 的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!