在 Vue 模板中渲染 table

Render table in Vue template

我正在尝试使用 header 和 body 数据从 object 渲染 table:

const mydata = {header: {}, body: {}}

这会产生两个 <table> 元素:

<template>
  <div class="container" id="ProbabilityTable">
    <div id="v-for-object">
      <table>
        <div v-for="(data, key) in table(html)">

          <thead v-if="key === 'header'">
            // render table header
          </thead>

          <tbody v-if="key === 'body'">          
            // render table body
          </tbody>

        </div>
      </table>
    </div>
  </div>
</template>

是这样的:

<template>
  <div class="container" id="ProbabilityTable">
    <div id="v-for-object">
      <table>
        <div v-for="(data, key) in table(html)">

          <thead v-if="key === 'header'">
            // render table header
          </thead>
          <tbody v-if="key === 'body'">          
            // render body header
          </tbody>

        </div>
      </table>
    </div>
  </div>
</template>

生成了一个 table,但它已损坏,因为 html table 中间不应该有 div。

有什么解决办法吗?

您发布的 2 个片段的解释相同。而且他们都错了。

如此处所述https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table div 不是表格的有效内容。正因为如此,每个浏览器都会以不同的方式解释错误。

解决方法:使用有效的HTML语法,看看问题是否仍然存在。

您可以使用 <template></template> 标签。

<template> 标签不会将自身呈现为元素,但您可以在 vue 中将其用于条件和循环。

<template>
<div class="container" id="ProbabilityTable">
   <div id="v-for-object">
     <table>
      <template v-for="(data, key) in table(html)">
        <thead v-if="key === 'header'">
        // render table header
        </thead>
        <tbody v-if="key === 'body'">          
        // render body header
        </tbody>
      </template>
      </table>
      </div>
    </div>
</template>

为您的页眉和主体做一个 for 循环,这样您就不需要制作额外的 div 或模板。

<table>
  <thead>
    <tr v-for="(row, headerKey) in table(html).header" :key="headerKey">
      <td>{{ row }}</td>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(row, bodyKey) in table(html).body" :key="bodyKey">
      <td>{{ row }}</td>
    </tr>
  </tbody>
</table>