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

如何在Quasar Table的body插槽中从嵌套字段渲染多列?

解决Quasar Table自定义插槽无法获取嵌套属性的问题

方法1:预处理API返回数据,将嵌套属性提至顶层

拿到API返回的数据后,把scan_settings下的字段提取到顶层对象中,让props.row[col.name]可以直接匹配到对应值:

// 假设API返回数据存在response变量中
const tableData = [
  {
    ...response.scan_settings // 展开嵌套属性到顶层
  }
]
// 将tableData传入q-table的rows属性即可

这种方式逻辑最简单,适合数据结构固定的场景,无需修改插槽和列定义的原有逻辑。

方法2:直接调用列定义中的field函数取值

既然你已经在列配置里通过field函数处理了嵌套路径的取值,那在自定义插槽里直接调用这个函数就能拿到对应值,不用再依赖props.row[col.name]:

修正列定义的field路径:

const columns = [
 {
  name: 'group_name',
  label: 'Qualys scan settings',
  field: row => row?.scan_settings?.group_name // 指向正确的嵌套路径
 },
 {
  name: 'profile_id',
  label: 'Qualys scan type',
  field: row => row?.scan_settings?.profile_id
 },
 // 其余列按此格式调整
]

修改插槽代码:

<template #body="props">
  <q-tr :props="props">
    <q-td
      v-for="col in props.cols"
      :key="col.name"
      :props="props"
      class="table-cell"
    >
      <span v-if="dateColumns.includes(col.name)">
        {{ parseISODateStringToLocale(col.field(props.row)) }}
      </span>
      <!-- 省略其他类型判断逻辑 -->
      <span v-else>
        {{ col.field(props.row) }}
      </span>
    </q-td>
  </q-tr>
</template>

方法3:自定义列路径属性,用通用函数取值

如果需要更灵活的嵌套值处理,可以给每个列添加path属性存储嵌套路径,再写一个通用函数根据路径取值:

列定义添加path属性:

const columns = [
 {
  name: 'group_name',
  label: 'Qualys scan settings',
  path: 'scan_settings.group_name'
 },
 {
  name: 'profile_id',
  label: 'Qualys scan type',
  path: 'scan_settings.profile_id'
 },
 // 其余列按此格式调整
]

编写通用取值函数:

// 可放在组件的methods或全局工具文件中
function getNestedValue(obj, path) {
  return path.split('.').reduce((current, key) => current?.[key], obj)
}

插槽中调用通用函数:

<template #body="props">
  <q-tr :props="props">
    <q-td
      v-for="col in props.cols"
      :key="col.name"
      :props="props"
      class="table-cell"
    >
      <span v-if="dateColumns.includes(col.name)">
        {{ parseISODateStringToLocale(getNestedValue(props.row, col.path)) }}
      </span>
      <!-- 省略其他类型判断逻辑 -->
      <span v-else>
        {{ getNestedValue(props.row, col.path) }}
      </span>
    </q-td>
  </q-tr>
</template>

内容的提问来源于stack exchange,提问作者Ira Ramírez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:55:24