Vue:如何在tbody中有条件地渲染tr

时间:2018-03-31 04:28:37

标签: vue.js

我有一个包含多行的表格,例如:

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

我想条件性地将v-if与v-for组合,以有条件地呈现一个或多个其他行。 Vue手册说要将v-for包装在v-if中,如下所示:

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

问题在于,我无法将div放入tbody或任何其他元素中。解决方案是什么?

2 个答案:

答案 0 :(得分:2)

在没有元素适合的情况下,you can use <template>,如:

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

演示:

&#13;
&#13;
new Vue({
  el: '#app',
  data: {
    showTwoRows: true
  }
})
&#13;
<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>
&#13;
&#13;
&#13;

虽然在你的具体例子中,但似乎并不需要。您是否尝试过不使用v-if

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

因为v-for的价值为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: '' } } })

&#13;
&#13;
<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>
&#13;
{{1}}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以在同一标签上使用v-forv-if,但是,它的工作方式与您预期的方式不同。

v-if中您可以引用迭代项目,因为在v-for之前执行了v-if

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

这仍将遍历positions中的所有team.positions,如果v-if中的条件未满足,则不会停止for循环,而是跳过它。

这样想:

for (var i = 0; i < array.length-1; i++) {
    if (array[i]) {
        doTheThing();
    }
}