Search code examples
vue.jshtml-tablev-for

Render table in Vue template


I am trying to render a table from an object with header and body data:

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

This produces two <table> elements:

<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>

were as this:

<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>

produces one table which is broken because there html tables should not have divs in the middle of them.

Is there any way around this?


Solution

  • You can use <template></template> tag.

    <template> tag doesn't render itself as an element, but you can use it for conditions and loops in 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>