Bootstrap Table formatter报undefined错误但数据显示正常的求助
问题排查与解决办法
报错原因分析
这个错误本质是appliance.activeAppliance为undefined时,代码直接访问warrantyDurationType导致的。哪怕用v-if控制表格渲染,Bootstrap Table的内部机制可能会在数据未完全就绪时提前调用formatter或sortByFormatted函数;另外也有可能接口返回的某条设备数据里,activeAppliance字段本身就缺失。
具体解决办法
在formatter和sortByFormatted函数里,给每一层对象访问加上可选链操作符?.,同时补充默认值处理,确保不会因为某一层为undefined而抛出错误:
修改后的字段配置代码:
{ key: 'activeAppliance.warrantyDuration', label: this.$t('warrantyDuration'), sortable: true, formatter: (warrantyDuration, applianceId, appliance) => { // 先确保activeAppliance存在,再取warrantyDurationType const durationType = appliance?.activeAppliance?.warrantyDurationType; const typeText = durationType ? this.$t(`model.appliance.warrantyDurationTypes.${durationType}`).toLocaleLowerCase(this.$i18n.locale) : ''; return `${this.$n(warrantyDuration)} ${typeText}`; }, sortByFormatted: (warrantyDuration, applianceId, appliance) => { // 同样先判断activeAppliance和warrantyDurationType是否存在 const durationType = appliance?.activeAppliance?.warrantyDurationType; return durationType === 'YEARS' ? (warrantyDuration * 12) : warrantyDuration; } }
额外检查点
- 可以在接口数据返回后,先过滤掉
activeAppliance为undefined的条目,或者给这些条目补充默认的activeAppliance空对象,避免后续处理出错:// 假设接口返回的数据存在this.applianceList中 this.applianceList = res.data.map(item => ({ ...item, activeAppliance: item.activeAppliance || {} }));
内容的提问来源于stack exchange,提问作者Maflec
相关产品推荐
相关产品推荐

