【问题标题】:"TypeError": Cannot read properties of undefined in Vuejs?“TypeError”:无法读取 Vuejs 中未定义的属性?
【发布时间】:2021-12-28 16:33:21
【问题描述】:

它的工作原理是这样的:我有一个用 Vue 制作的表格,其中有一些选择选项。当我有一个 grupo(组)并且该组与 maquina(机器)没有关联时会出现此错误,不应该发生什么,目标是只出现“-”。在控制台中引发错误,并且不会显示在我的 DataTable 中。

错误:[/Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'id_area')

这是我认为导致此错误的代码部分:

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
                ]
            });
        });
    }
},

有人可以帮助我吗?我不明白为什么会这样。

【问题讨论】:

    标签: javascript node.js vue.js vuejs2 datatable


    【解决方案1】:

    如果未找到该值 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find),则 array.find() 方法返回 undefined

    因此,如果从上一行检索到没有 ID 为 group.id_maquina 的“machina”,则 const machine = this.maquinas.find(m => m.id === group.id_maquina); 行将值 undefined 设置为 machine 常量。

    这是你的错误发生:从machine读取id_area未定义。

    所以你必须检查你的变量在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);
        }
      }
    //...
    

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 2020-11-08
      • 2017-09-16
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 2020-11-23
      • 1970-01-01
      相关资源
      最近更新 更多