如何在Vue.js中使用嵌套for循环遍历嵌套结构数据
问题分析与解决
你的代码出现employee not defined以及empId相关错误,核心问题有三个:
- 遍历逻辑错误:
tableEmployeeList是对象,第一层循环拿到的employee是每个键(01/02/03)对应的值,也就是{ missing: [...] },这个对象本身没有empId属性;第二层循环data in employee是遍历对象的键名(即"missing"字符串),自然找不到data.empId。 - HTML结构非法:
<tr>不能直接嵌套<tr>,浏览器会自动修正DOM结构,导致循环变量作用域混乱,触发employee not defined。 - 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
相关产品推荐
相关产品推荐

