Vue.js Conditional Statements

Conditional Judgment

v-if

Conditional judgment using the v-if directive:

v-if Directive

Using the v-if directive on elements and templates:

<div id="app"> <p v-if="seen">Now you see me</p> <template v-if="ok"> <h1>Example Tutorial</h1> <p>What you learn is not only technology, but also dreams!</p> <p>Hahaha, typing is hard work!!!</p> </template> </div> <script> new Vue({ el: '#app', data: { seen: true, ok: true } }) </script>

Try it Yourself »

Here, the v-if directive will decide whether to insert the p element based on the value of the expression seen (true or false).

In string templates, such as Handlebars, we had to write a conditional block like this:

<!-- Handlebars 模板 -->
{{#if ok}}
  <h1>Yes</h1>
{{/if}}

v-else

You can use the v-else directive to add an "else" block to v-if:

v-else Directive

Randomly generate a number, determine whether it is greater than 0.5, and then output the corresponding information:

<div id="app"> <div v-if="Math.random() > 0.5"> Sorry </div> <div v-else> Not sorry </div> </div> <script> new Vue({ el: '#app' }) </script>

Try it Yourself »

v-else-if

v-else-if, added in 2.1.0, as the name suggests, is used as an else-if block for v-if. It can be chained multiple times:

v-else Directive

Determine the value of the type variable:

<div id="app"> <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> </div> <script> new Vue({ el: '#app', data: { type: 'C' } }) </script>

Try it Yourself »

v-else and v-else-if must follow a v-if or v-else-if.

v-show

We can also use the v-show directive to conditionally display elements:

v-show Directive

<h1 v-show="ok">Hello!</h1>

Try it Yourself »
Other Extensions