Easy Tutorial
❮ Home Vue Watch ❯

Vue.js Conditional Statements

Conditional Rendering

v-if

Conditional rendering is done using the v-if directive:

v-if Directive

Use 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>tutorialpro.org</h1>
      <p>Learning is not only about technology, but also about dreams!</p>
      <p>Hahaha, typing is hard!!!</p>
    </template>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    seen: true,
    ok: true
  }
})
</script>

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

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

<!-- Handlebars Template -->
{{#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

Generate a random number and determine if it is greater than 0.5, then output the corresponding message:

<div id="app">
    <div v-if="Math.random() > 0.5">
      Sorry
    </div>
    &lt;div v-else>
      Not sorry
    </div>
</div>

<script>
new Vue({
  el: '#app'
})
</script>

v-else-if

v-else-if was added in 2.1.0, as the name suggests, it serves 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>
    &lt;div v-else>
      Not A/B/C
    </div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    type: 'C'
  }
})
</script>

>

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

v-show

We can also use the v-show directive to display elements based on a condition:

v-show Directive

<h1 v-show="ok">Hello!</h1>
❮ Home Vue Watch ❯