What are the most commonly used Directives in Vue.js?

There are a set of directives in Vue.js used to show or hide elements according to the conditions. These directives are also known as conditional directives.

  • v-if
  • v-else
  • v-else-if
  • v-show
  • v-model
  • v-on

v-if directive: The v-if directive is used to add or remove the DOM elements based on the given expression. For example, the below button will not show if isLoggedIn if you set it to false.

  1. <button v-if=”isLoggedIn”>Logout</button>  

The v-if directive also facilitates you to 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 conditionally apply both label and button together.

  1. <template v-if=”isLoggedIn”>  
  2.   <label> Logout </button>  
  3.   <button> Logout </button>  
  4. </template>  

v-else directive: The v-else directive is used to display content only when the expression adjacent v-if set to false. This is same as 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).

  1. <button v-if=”isLoggedIn”> Logout </button>  
  2. <button v-else> Log In </button>  

v-else-if directive: The v-else-if directive is used when you want more than two options to be checked. For example, if you want to display some text instead of LogIn button when ifLoginDisabled property is set to true, you can achieve this through v-else statement.

  1. <button v-if=”isLoggedIn”> Logout </button>  
  2. <label v-else-if=”isLoginDisabled”> User login disabled </label>  
  3. <button v-else> Log In </button>  

v-show directive: The v-show 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 preferred if you want the elements to switch on and off frequently.

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