Vue: Conditional Rendering
2022-03-20
0. Intro
通过 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 .
<template v-if="ok">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</template>
2. v-show
跟 v-if
的最大区别是不改变 DOM,只改变 css display property,而且不支持 <template>
和 v-else
<h1 v-show="ok">Hello!</h1>
v-if vs v-show
假如经常变,就用 v-show,假如很少变,就用 v-if。
v-if
has higher toggle costs, v-if is real conditional (destroy the element and recreate), it is also lazy.v-show
has higher initial render costs, using css to toggle
So prefer v-show
if you need to toggle something very often, and prefer v-if
if the condition is unlikely to change at runtime.