You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue.js中使用嵌套for循环遍历嵌套结构数据

问题分析与解决

你的代码出现employee not defined以及empId相关错误,核心问题有三个:

  1. 遍历逻辑错误:tableEmployeeList是对象,第一层循环拿到的employee是每个键(01/02/03)对应的值,也就是{ missing: [...] },这个对象本身没有empId属性;第二层循环data in employee是遍历对象的键名(即"missing"字符串),自然找不到data.empId。
  2. HTML结构非法:<tr>不能直接嵌套<tr>,浏览器会自动修正DOM结构,导致循环变量作用域混乱,触发employee not defined。
  3. Key绑定错误:第一层循环的key绑定了不存在的employee.empId,不符合Vue的key绑定规则。

正确写法(根据需求选择)

需求1:每个部门(01/02/03)占一行,展示该部门下的缺失员工

<tbody>
  <!-- 遍历tableEmployeeList的每个部门,item是包含missing数组的对象 -->
  <tr v-for="(item, deptKey) in tableEmployeeList" :key="deptKey">
    <!-- 遍历当前部门的缺失员工列表 -->
    <td class="td-empId" v-for="emp in item.missing" :key="emp.empId">
      {{ emp.empId }}
    </td>
  </tr>
</tbody>

需求2:每个缺失员工单独占一行

用<template>作为外层循环容器(不会渲染成实际DOM元素),避免非法嵌套:

<tbody>
  <!-- 遍历所有部门 -->
  <template v-for="(item, deptKey) in tableEmployeeList" :key="deptKey">
    <!-- 遍历当前部门的缺失员工,每个员工一行 -->
    <tr v-for="emp in item.missing" :key="emp.empId">
      <td class="td-empId">{{ emp.empId }}</td>
    </tr>
  </template>
</tbody>

内容的提问来源于stack exchange,提问作者P.S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 11:40:36