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

Vue.js中如何渲染多个自定义动态表格

Vue 渲染多个自定义动态表格

基于之前单个动态表格的实现逻辑,我们可以直接扩展来处理多表格场景,以下是针对给定JSON结构的实现方案:

模板代码

<template>
  <div>
    <!-- 遍历每个表格配置,生成独立表格 -->
    <div v-for="table in tables" :key="table.id" class="s-table-container">
      <table class="s-table">
        <thead>
          <tr>
            <!-- 渲染当前表格的表头 -->
            <th v-for="header in table.headers" :key="header.id">{{ header.header_name }}</th>
          </tr>
        </thead>
        <tbody>
          <!-- 渲染当前表格的每一行 -->
          <tr v-for="rowId in getRowIds(table.headers)" :key="rowId">
            <td v-for="header in table.headers" :key="header.id">
              {{ getCellValue(header.colVal, rowId) }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

脚本逻辑

<script setup>
import { ref } from 'vue'

// 模拟API返回的多表格数据
const tables = ref([
  {
    "id": 1, 
    "enabled": true,
    "headers": [
        {
          "id": 1, 
          "header_name": "LastName",
          "colVal": [{ "id": 1, "value": "Hopper" },
                    { "id": 3, "value": "Lovelace"}]
        }, 
        {
          "id": 2, 
          "header_name": "FirstName",
          "colVal": [{ "id": 1, "value": "Grace" },
                    { "id": 4, "value": "Ada" }]
        }
     ]
  }, 
  {
    "id": 2, 
    "enabled": true,
    "headers": [
        {
          "id": 1, 
          "header_name": "Age",
          "colVal": [{ "id": 1, "value": 22 },
                    { "id": 3, "value": 31}]
        }, 
        {
          "id": 2, 
          "header_name": "Phone Number",
          "colVal": [{ "id": 1, "value": "123-456" },
                    { "id": 4, "value": "789-543" }]
        }
     ]
  }
])

// 提取当前表格所有的行ID(去重,确保每行唯一)
const getRowIds = (headers) => {
  const rowIds = new Set()
  headers.forEach(header => {
    header.colVal.forEach(cell => rowIds.add(cell.id))
  })
  return Array.from(rowIds)
}

// 根据行ID匹配对应列的单元格值
const getCellValue = (colVals, rowId) => {
  const targetCell = colVals.find(item => item.id === rowId)
  return targetCell ? targetCell.value : ''
}
</script>

样式配置

<style scoped>
.s-table-container {
  margin: 20px 0;
}
.s-table {
  border-collapse: collapse;
  width: 100%;
}
.s-table th, .s-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}
.s-table th {
  background-color: #f2f2f2;
}
</style>

核心逻辑说明

  • 外层通过v-for遍历整个表格数组,为每个表格配置生成独立的表格容器和表格结构
  • getRowIds函数从当前表格的所有表头列数据中,提取并去重得到所有行的唯一ID,确保每行能对应所有列的数据
  • getCellValue函数根据行ID,在当前列的colVal数组中匹配对应单元格的值,完成行列数据的对应渲染

内容的提问来源于stack exchange,提问作者doozy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:45:06