Vue - 尝试显示嵌套对象中的数据时呈现错误

Vue - error in render when trying to display data from nested object

我正在处理 Vue 中的一个奇怪问题。我正在尝试显示 table 中的员工列表。员工由 REST 服务提供,响应看起来完全像这样(下面显示的是 paginatedList 中的一项):

{
  "id": 10a,
  "code": 0000,
  "firstName": "John",
  "lastName": "Doe",
  "level": "WORKER",
  "specialization": {
    "id": 20,
    "name": "Default",
    "taem": {
      "id": 2,
      "name": "Builders",
      "system": false,
      "teamLead": null,
      "specializationDtos": null,
      "categoryDtos": null
    }
  },
  "team": {
    "id": 2,
    "name": "Builders",
    "system": false,
    "teamLead": null,
    "specializationDtos": null,
    "categoryDtos": null
  },
  "coachDto": null,
  "roles": [
    "DL"
  ]
}

在 Vue 中,我使用 Vuex 操作来预处理原始数据和 return 分页的员工列表。然后我尝试使用 v-for 在 table 中打印它,如下所示:

<tr v-for="item in paginatedList" :key="item.id"
  v-on:click="selectRow(item)"
  v-bind:class="{selectedRow: selectedItem === item}"
>
  <td>{{item.id}}</td>
  <td>{{item.name}}</td>
  <td>{{item.team.name}}</td>
</tr>

这就是它失败的地方(有点)。即使显示 table 且没有员工遗漏团队名称,我还是从 Vue 收到警告:

[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"

单击导致警告的代码行后,它指向我尝试渲染的地方{{item.team.name}}

我的第一个想法是没有显示缺少团队的员工。为了检查它,我想出了以下解决方法:

<td>{{getTeamName(item.team)}}</td>

以及方法:

getTeamName(team) {
  return (team ? team.name : 'FAILED');
}

Warning/error 消失了,但是 FAILED 团队没有员工。这到底是什么问题?是否可以像那样显示嵌套对象的属性,还是应该避免?

当您迭代的对象还没有您期望的数据,但当您调试它时,它已经有了。在使用从承诺中获得的数据时,我最常发现这一点。考虑到这一点,只需添加一个检查以确保您的数据已正确加载,在您的情况下,这就足够了:

<tr v-for="item in paginatedList" :key="item.id"
  v-on:click="selectRow(item)"
  v-bind:class="{selectedRow: selectedItem === item}"
>
  <div v-if="item.team">
    <td>{{item.id}}</td>
    <td>{{item.name}}</td>
    <td>{{item.team.name}}</td>
  </div>
</tr>

我的组件上通常有一个 dataLoaded 属性,它初始化为 false,但在我处理完数据后设置为 true 以避免此类问题。然后我会检查 v-if="dataLoaded" 我的整个组件。

您的对象中似乎有拼写错误的团队:

 "taem": {
      "id": 2,
      "name": "Builders",
      "system": false,
      "teamLead": null,
      "specializationDtos": null,
      "categoryDtos": null
    }

我想这就是它无法呈现未定义名称的原因。