[英]"TypeError": Cannot read properties of undefined in Vuejs?
It works like this: I have a table made in Vue, where I have some select options.它的工作原理是这样的:我有一个用 Vue 制作的表格,其中有一些 select 选项。 This error appears when I have a grupo (group) and this group is not associated with a maquina (machine), what shouldn't happen, the objective is that only "-" appears.当我有一个 grupo(组)并且该组与 maquina(机器)没有关联时会出现此错误,不应该发生什么,目标是只出现“-”。 Throws an error in the console and does not show in my DataTable.在控制台中引发错误,并且不会显示在我的 DataTable 中。
The error: [/Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'id_area')
错误: [/Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'id_area')
This is the part of my code that I believe is causing this error:这是我认为导致此错误的代码部分:
computed: {
linhas () {
return this.lista.map(row => {
const group = this.grupos.find(g => g.id === row.id_grupo);
const machine = this.maquinas.find(m => m.id === group.id_maquina);
const area = this.areas.find(a => a.id === machine.id_area);
return ({
href: {path: this.editRoute + row.id},
cols: [
row.id,
row.tag,
row.descricao,
row.tipo === "ANALOGICA" ? "Analógica" : "Digital",
group.nome,
(machine || { nome: "-" }).nome,
(area || { nome: "-" }).nome
]
});
});
}
},
Can someone help me?有人能帮我吗? I do not understand why this happening.我不明白为什么会这样。
The array.find() method returns undefined
if the value is not found ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find ).如果未找到该值,则 array.find() 方法返回undefined
( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find )。
So if ther is no "machina" with the id group.id_maquina
retrieve from the previous line, the line const machine = this.maquinas.find(m => m.id === group.id_maquina);
因此,如果从上一行中检索到的 ID group.id_maquina
的“machina”不存在,则行const machine = this.maquinas.find(m => m.id === group.id_maquina);
set value undefined
to the machine
const.将值undefined
设置为machine
常量。
And here's your error happens: reading id_area
from machine
that is undefined.这是你的错误发生:从未定义的machine
读取id_area
。
So you have to check if your variables are not undefined after array.find()
所以你必须检查你的变量在array.find()
之后是否未定义
//...
const group = this.grupos.find(g => g.id === row.id_grupo);
if (group) {
const machine = this.maquinas.find(m => m.id === group.id_maquina);
if (machine) {
const area = this.areas.find(a => a.id === machine.id_area);
}
}
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.