• Home
  • Recent Q&A
  • Java
  • Cloud
  • JavaScript
  • Python
  • SQL
  • PHP
  • HTML
  • C++
  • Data Science
  • DBMS
  • Devops
  • Hadoop
  • Machine Learning
in Vue.JS by
What are the conditional directives in VueJS?

1 Answer

0 votes

VueJS provides set of directives to show or hide elements based on conditions. The available directives are: v-if, v-else, v-else-if and v-show

1. v-if: The v-if directive adds or removes DOM elements based on the given expression. For example, the below button will not show if isLoggedIn is set to false.

<button v-if="isLoggedIn">Logout</button>

You can also control multiple elements with a single v-if statement by wrapping all the elements in a <template> element with the condition. For example, you can have both label and button together conditionally applied,

<template v-if="isLoggedIn">

  <label> Logout </button>

  <button> Logout </button>


2. v-else: This directive is used to display content only when the expression adjacent v-if resolves to false. This is similar to else block in any programming language to display alternative content and it is preceded by v-if or v-else-if block. You don't need to pass any value to this. For example, v-else is used to display LogIn button if isLoggedIn is set to false(not logged in).

<button v-if="isLoggedIn"> Logout </button>

<button v-else> Log In </button>

3. v-else-if: This directive is used when we need more than two options to be checked. For example, we want to display some text instead of LogIn button when ifLoginDisabled property is set to true. This can be achieved through v-else statement.

<button v-if="isLoggedIn"> Logout </button>

<label v-else-if="isLoginDisabled"> User login disabled </label>

<button v-else> Log In </button>

4. v-show: This directive is similar to v-if but it renders all elements to the DOM and then uses the CSS display property to show/hide elements. This directive is recommended if the elements are switched on and off frequently.

<span v-show="user.name">Welcome user,{{user.name}}</span>

Related questions

0 votes
asked Feb 4, 2020 in Vue.JS by rajeshsharma
0 votes
asked Feb 4, 2020 in Vue.JS by rajeshsharma