Bootstrap Vue b-table显示嵌套对象属性报未定义错误解决方法
b-table渲染嵌套字段报未定义错误
问题现象
尝试在bootstrap-vue的b-table组件中展示订单绑定的司机信息:
- 控制台直接执行
console.log(this.orders[0].order_drivers[0].populated_driver.user.username)可以正常获取到第一条订单的司机名称 - 表格渲染对应字段时抛出错误:
data.item.order_drivers[0] is not defined
初始实现代码
<b-table :items="orders" :fields="fields" :per-page="perPage" :current-page="currentPage" :filter="filter" :filter-function="filterDate" :sort-by.sync="sortBy" :sort-desc.sync="sortDesc" sort-icon-left small > <template #cell(status)="data"> <div class="text-nowrap"> <span class="align-text-top text-capitalize">{{ data.item.status }}</span> </div> </template> <template #cell(order_number)="data"> <div class="text-nowrap"> <span class="align-text-top text-capitalize">{{ data.item.order_number}}</span> </div> </template> <template #cell(deliver_date)="data"> <span class="align-text-top text-capitalize">{{ data.item.deliver_date }}</span> </template> <template #cell(pickup_date)="data"> <span class="align-text-top text-capitalize">{{ data.item.pickup_date }}</span> </template> <template #cell(subtotal)="data"> <div class="text-nowrap"> <span class="align-text-top text-capitalize">{{ data.item.subtotal }}</span> </div> </template> <template #cell(tip)="data"> <div class="text-nowrap"> <span class="align-text-top text-capitalize">{{ data.item.tip_from_restaurant }}</span> </div> </template> <template #cell(additional_tip)="data"> <div class="text-nowrap"> <span class="align-text-top text-capitalize">{{ data.item.extra_tip_from_restaurant }}</span> </div> </template> <template #cell(tfr_tip)="data"> <div class="text-nowrap"> <span class="align-text-top text-capitalize">{{ data.item.tip_from_tfr }}</span> </div> </template> <template #cell(tfr_additional_tip)="data"> <div class="text-nowrap"> <span class="align-text-top text-capitalize">{{ data.item.extra_tip_from_tfr }}</span> </div> </template> <template #cell(driver)="data"> <div class="text-nowrap"> <span class="align-text-top text-capitalize">{{ data.item.order_drivers[0].populated_driver.user.username}}</span> </div> </template> </b-table>
问题原因
接口返回的订单列表中,存在部分订单未绑定司机的情况,这类订单的order_drivers字段为空数组。表格遍历渲染所有行时,遇到空数组直接取下标为0的元素就会触发未定义错误。控制台测试时只取了第一条有司机的订单数据,所以能正常输出结果。
修复方案
在司机列渲染时增加条件判断:当当前行订单的order_drivers数组长度不为0时,再读取嵌套的司机用户名;否则显示兜底文案None.。
修复后的司机列代码如下:
<template #cell(driver)="data"> <div class="text-nowrap"> <span class="align-text-top text-capitalize" v-if="orders[data.index].order_drivers.length!==0" >{{ data.item.order_drivers[0].populated_driver.user.username}}</span> <span class="align-text-top text-capitalize" v-else>None.</span> </div> </template>
内容的提问来源于stack exchange,提问作者user15899845
相关产品推荐
相关产品推荐

