# 條件渲染
[](https://vuefe.cn/guide/conditional.html#v-if)
## [](https://vuefe.cn/guide/conditional.html#v-if)[](https://vuefe.cn/guide/conditional.html#v-if "v-if")v-if
在字符串模板中,如 Handlebars ,我們得像這樣寫一個條件塊:
~~~
<!-- Handlebars 模板 -->{{#if ok}} <h1>Yes</h1>{{/if}}
~~~
在 Vue.js ,我們使用?`v-if`?指令實現同樣的功能:
~~~
<h1 v-if="ok">Yes</h1>
~~~
也可以用?`v-else`?添加一個 “else” 塊:
~~~
<h1 v-if="ok">Yes</h1><h1 v-else>No</h1>
~~~
[](https://vuefe.cn/guide/conditional.html#template-v-if)
### [](https://vuefe.cn/guide/conditional.html#template-v-if)[](https://vuefe.cn/guide/conditional.html#template-v-if "template v-if")template v-if
因為?`v-if`?是一個指令,需要將它添加到一個元素上。但是如果我們想切換多個元素呢?此時我們可以把一個?`<template>`?元素當做包裝元素,并在上面使用?`v-if`,最終的渲染結果不會包含它。
~~~
<template v-if="ok"> <h1>Title</h1> <p>Paragraph 1</p> <p>Paragraph 2</p></template>
~~~
[](https://vuefe.cn/guide/conditional.html#v-else)
### [](https://vuefe.cn/guide/conditional.html#v-else)[](https://vuefe.cn/guide/conditional.html#v-else "v-else")v-else
可以用?`v-else`?指令給?`v-if`?或?`v-show`?添加一個 “else” 塊:
~~~
<div v-if="Math.random() > 0.5"> Sorry</div><div v-else> Not sorry</div>
~~~
`v-else`?元素必須緊跟在?`v-if`?或?`v-show`?元素的后面——否則它不能被識別。
[](https://vuefe.cn/guide/conditional.html#v-show)
### [](https://vuefe.cn/guide/conditional.html#v-show)[](https://vuefe.cn/guide/conditional.html#v-show "v-show")v-show
另一個根據條件展示元素的選項是?`v-show`?指令。用法大體上一樣:
~~~
<h1 v-show="ok">Hello!</h1>
~~~
不同的是有?`v-show`?的元素會始終渲染并保持在 DOM 中。`v-show`?是簡單的切換元素的 CSS 屬性?`display`?。
注意?`v-show`?不支持?`<template>`?語法。
[](https://vuefe.cn/guide/conditional.html#v-if-vs-v-show)
## [](https://vuefe.cn/guide/conditional.html#v-if-vs-v-show)[](https://vuefe.cn/guide/conditional.html#v-if-vs-v-show "v-if vs. v-show")v-if vs. v-show
`v-if`?是真實的條件渲染,因為它會確保條件塊在切換當中適當地銷毀與重建條件塊內的事件監聽器和子組件。
`v-if`?也是惰性的:如果在初始渲染時條件為假,則什么也不做——在條件第一次變為真時才開始局部編譯(編譯會被緩存起來)。
相比之下,?`v-show`?簡單得多——元素始終被編譯并保留,只是簡單地基于 CSS 切換。
一般來說,?`v-if`?有更高的切換消耗而?`v-show`?有更高的初始渲染消耗。因此,如果需要頻繁切換使用?`v-show`?較好,如果在運行時條件不大可能改變則使用?`v-if`?較好。