我有一个包含多行的表体,例如:
<table>
<tbody>
<tr>...</tr>
<tr>...</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
我想有条件地组合 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>
Run Code Online (Sandbox Code Playgroud)
问题是我不能将 div 放在 tbody 或任何其他元素中。解决办法是什么?
在没有元素适合的情况下,您可以使用<template>,例如:
<template v-if="team.positions != null">
<my-row v-for="position in team.positions"
:position="position"
:key="position.id">
</my-row>
</template>
Run Code Online (Sandbox Code Playgroud)
演示:
new Vue({
el: '#app',
data: {
showTwoRows: true
}
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
虽然在你的那个具体例子中,它似乎并不需要。您是否尝试过根本不使用v-if:
<my-row v-for="position in team.positions"
:position="position"
:key="position.id">
</my-row>
Run Code Online (Sandbox Code Playgroud)
因为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: ''
}
}
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)