Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue: How to conditionally render tr in tbody

Tags:

vue.js

I have a table body with multiple rows, such as this:

<table>
<tbody>
<tr>...</tr>
<tr>...</tr>
</tbody>
</table>

I want to conditionally combine v-if an v-for, to conditionally render one or more additional rows. The Vue manual says to wrap the v-for in a v-if, such as follows:

<div v-if="team.positions != null">
    <my-row v-for="position in team.positions"
                :position="position"
                :key="position.id">
    </my-row>
</div>

The problem is that I can't put a div in a tbody, or any other element for that matter. What's the solution?

like image 477
DatsunBing Avatar asked Mar 31 '18 04:03

DatsunBing


1 Answers

In those situations where no element would fit, you can use <template>, like:

<template v-if="team.positions != null">
    <my-row v-for="position in team.positions"
                :position="position"
                :key="position.id">
    </my-row>
</template>

Demo:

new Vue({
  el: '#app',
  data: {
    showTwoRows: true
  }
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <table>
    <tr>
      <td>A</td><td>B</td>
    </tr>
    <template v-if="showTwoRows">
      <tr>
        <td>1</td><td>2</td>
      </tr>
      <tr>
        <td>3</td><td>4</td>
      </tr>
    </template>
    <tr>
      <td>C</td><td>D</td>
    </tr>
  </table>
  <button @click="showTwoRows = !showTwoRows">Toggle two middle rows</button>
</div>

Though in that specific example of yours, it doesn't seem needed. Have you tried simply not using the v-if:

<my-row v-for="position in team.positions"
            :position="position"
            :key="position.id">
</my-row>

Because the v-for just won't iterate (without throwing errors) if its value is undefined/null/0/[]/'':

new Vue({
  el: '#app',
  data: {
    message: "If I'm being displayed, Vue works!",
    team: {
      positionsU: undefined,
      positionsN: null,
      positionsZ: 0,
      positionsE: [],
      positionsS: ''
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
  <table>
    <tr v-for="position in team.positionsU"><td>u: {{ position }}</td></tr>
    <tr v-for="position in team.positionsN"><td>n: {{ position }}</td></tr>
    <tr v-for="position in team.positionsZ"><td>z: {{ position }}</td></tr>
    <tr v-for="position in team.positionsE"><td>e: {{ position }}</td></tr>
    <tr v-for="position in team.positionsS"><td>s: {{ position }}</td></tr>
    <tr v-for="position in team.positionsF"><td>f: {{ position }}</td></tr>
  </table>
</div>
like image 147
acdcjunior Avatar answered Oct 18 '22 08:10

acdcjunior