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

VueJS中渲染嵌套JSON数据生成表格时如何去除多余空行

Vue 渲染JSON表格顶部3行空行问题修复

问题现象

基于本地JSON文件渲染商品表格时,有效数据行上方固定出现3行空白行,效果如下:
表格空行问题截图

关联测试JSON文件(test.json)结构:

{
  "country": {
    "us": {
      "countryName": "USA",
      "items": {
        "itemId0001": {
          "name": "Basketball",
          "price": 500,
          "productImage": "local-placeholder-path/image.png"         
        },
        "itemId0002": {
          "name": "Soccer ball",
          "price": 800,
          "productImage": "local-placeholder-path/image.png"
        }
      }
    }
  }
}

问题根因

空行完全是v-for遍历层级错误生成的无效DOM导致:

  • 原代码在<tbody>标签上绑定了v-for="productList in countryList",会遍历countryList(即美国数据对象)的所有可枚举属性:countryName(字符串类型)、items(商品集合对象)
  • 遍历countryName属性时,其值为字符串"USA",长度为3,v-for遍历字符串会按字符索引循环3次,生成3行无有效字段的空表格行,和你看到的3行空行现象完全匹配
  • 只有遍历items属性时才会渲染出你需要的有效商品数据。

修复方案

调整v-for遍历目标,仅针对商品数据所在的items字段做行循环,移除不必要的嵌套遍历,修正后的完整组件代码如下:

<template>
<div class="container" style="width: 80%;">
  <div v-for="(regionInfo, regionKey) in data.country" :key="regionKey" style="margin-top: 50px">
    <h4>{{ regionInfo.countryName }}</h4>    
    <table>
      <thead>
        <tr>
            <th>商品名称</th>
            <th>价格</th>
            <th>商品图片地址</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(product, productId) in regionInfo.items" :key="productId">
          <td>{{ product.name }}</td>
          <td>{{ product.price }}</td>
          <td>{{ product.productImage }}</td>
        </tr>            
      </tbody>
    </table>
  </div>
</div>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</template>

<script> 
  import jsonData from '../assets/test.json'
  export default {
    data(){
      return{
        data: jsonData
      }
    }
  }
</script>

修复要点

  • 单个<table>仅保留1个<tbody>标签即可,不需要给<tbody>套多余的v-for循环
  • v-for遍历普通JS对象时,会遍历对象所有可枚举属性,必须明确指定要遍历的目标字段(比如这里的regionInfo.items),避免把非目标属性纳入循环生成无效DOM
  • 原代码中div上的width="80%"属于原生标签属性,改用CSSwidth: 80%写法更符合前端规范
  • 原表头列名和实际渲染的商品字段不匹配,已同步修正对应关系

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 12:33:12