Luna Tech

Tutorials For Dummies.

Vue: Conditional Rendering

2022-03-20


0. Intro

Reference

通过 v-if 和 v-else, v-else-if directive 来完成。

v-if toggles the existence of the element based on the truthiness of the condition.

v-else can be used to indicate an “else block” for v-if.

A v-else element must immediately follow a v-if or a v-else-if element - otherwise it will not be recognized. Similar to v-else, a v-else-if element must immediately follow a v-if or a v-else-if element.

Example

<button @click="awesome = !awesome">Toggle</button>

<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no 😢</h1>

v-else-if Example

<div v-if="type === 'A'">A</div>
<div v-else-if="type === 'B'">B</div>
<div v-else-if="type === 'C'">C</div>
<div v-else>Not A/B/C</div>

1. v-if on <template>

假如我们要 toggle more than one element,怎么办?

可以在 <template> 上用 v-if.

v-else and v-else-if can also be used on