【发布时间】:2019-07-02 23:15:32
【问题描述】:
我的 vue.js 应用中有一些组件遵循以下结构,它们都抛出相同的错误。
TypeError: Cannot read property 'id' of undefined
我认为通过将{{ jobs[0].id }} 与<template :v-if="jobs"> 或<template :v-if="jobs[0].id"> 包装起来会很容易解决,因为大多数其他stackoverflow 帖子都指出这是一种解决方案,但这确实使错误消失了。有趣的是下面的代码,所有数据(包括 id)都可以很好地呈现到页面,页面中没有数据丢失,但是 console.log 继续显示属性未定义错误,我的单元测试也失败了错误。
<template>
<div class="emptyDiv">
<h3>
Latest Build -
<router-link:to="{name: 'job_details'}">
{{ jobs[0].id }}
</router-link>
</h3>
</div>
<template>
<script>
export default {
name: "Stages",
data() {
return {
jobs: []
};
},
created() {
this.JobExecEndpoint =
process.env.VUE_APP_TEST_URL +
"/api/v2/job/"
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.jobs.push({
name: body[0].job.name,
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 };
});
}
};
</script>
我在这里做错了什么?我已经尝试解决这些错误大约 10 个小时,但一直无法解决。
更新:
我能够摆脱这些错误并通过添加我的单元测试
.then(() => {
this.new_id = this.jobs[0].id
})
到创建的块并在数据下添加 new_id=''
然后从模板调用new_id。但是,这不是一个令人满意的解决方案,因为我仍然不知道为什么它会在原始代码中引发错误,而且我不相信这个解决方案适用于一个完整的数组(不止一项工作)。
【问题讨论】:
-
错误发生在哪一行?是因为正文没有字段
id还是因为您使用键build_id推动它但在模板中定义了id? -
build_id 是我帖子中的错字,我修复了 OP。身体确实有身份。这已得到确认,也如前所述,id 确实呈现到页面,所以我不确定。
-
控制台,单元测试失败不会指向特定行
-
我已经用更多信息更新了操作
标签: javascript vue.js