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

Vue.js层级表格无法显示数据问题求助

Vue层级表格无法显示数据的解决方法

问题核心是HTML表格结构不合法:你把子<tr>直接嵌套在了父<tr>内部,而根据HTML规范,<tr>必须作为<tbody>、<thead>或<tfoot>的直接子元素,不能嵌套在其他<tr>里,这会导致浏览器解析失败,进而表格无法显示数据。

修正方案

将父行和子行都放在<tbody>的同级层级,或用<tbody>分组每个父项及其子项(结构更清晰)。以下是修正后的代码:

HTML部分

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Parent</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody v-for="item in items" :key="item.id">
    <!-- 父行 -->
    <tr>
      <td>{{ item.name }}</td>
      <td>{{ item.parent }}</td>
      <td>
        <button @click="toggleChildren(item)">Toggle Children</button>
      </td>
    </tr>
    <!-- 子行,仅在childrenVisible为true时显示 -->
    <tr v-if="item.childrenVisible" v-for="child in item.children" :key="child.id">
      <td>{{ child.name }}</td>
      <td>{{ child.parent }}</td>
      <td>
        <button @click="toggleChildren(child)">Toggle Children</button>
      </td>
    </tr>
  </tbody>
</table>

脚本补充优化

  1. 确保toggleChildren方法正确切换状态:
methods: {
  toggleChildren(item) {
    item.childrenVisible = !item.childrenVisible;
  }
}
  1. 初始化数据时给每个项默认添加childrenVisible: false,避免未定义状态导致的渲染异常:
data() {
  return {
    items: [
      {
        id: 1,
        name: "Parent 1",
        parent: "",
        childrenVisible: false,
        children: [
          { id: 11, name: "Child 1-1", parent: "Parent 1", childrenVisible: false },
          { id: 12, name: "Child 1-2", parent: "Parent 1", childrenVisible: false }
        ]
      },
      // 其他数据项
    ]
  };
}

修改后表格结构符合HTML规范,数据能正常渲染,子项的展开/折叠功能也可正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:01:27