1、问题描述:
<el-table-column label="控制箱" align="center" prop="boxId" :formatter="boxFormatter"/>
// 使用此方法一直无法成功回显
boxFormatter(row,column){
this.boxAllList.forEach(box => {
if(box.id == row.boxId){
return box.controlBoxName;
}
});
},
// 使用此方法可以正常回显
boxFormatter(row,column){
for (let i = 0; i < this.boxAllList.length; i++) {
if(this.boxAllList[i].id == row.boxId){
return this.boxAllList[i].controlBoxName;
}
}
},
2、原因分析
第一个 formatter 方法使用了 'forEach' 方法来遍历数组,但是 'forEach' 循环中使用 “return” 并不能直接返回值给 “formatter” 函数。这是因为 “return” 语句只会退出当前的循环回调函数,而不会返回值给 “formatter” 函数。
使用 for 循环来返回就可以返回正常,因为没有循环回调函数。