Conditional Directives Vue.js

Conditional Directives provide the ability to show or hide elements based on conditions is a fundamental feature of any frontend framework. Vue.js provides us with a set of core directives to achieve this effect: v-ifv-elsev-else-if and v-show.

After getting started with a Vue.js Hello World application, we can use values from JavaScript data object to conditionally control the view.

Conditional Directives in Vue.JS

  • v-if
  • v-else
  • v-else-if
  • v-show

For example, we’ll see how to use the simple boolean variable in your data construct below.

data() {
  return {
    msg: "Hello World!",
    isLoggedIn: false
  }
}

v-if

The v-if directive is used to add or remove HTML content from DOM depending upon a given condition to the directive. For example, we can show or hide a div with msg variable based on the above given isLoggedIn variable.

<div v-if="isLoggedIn">{{msg}}</div>

Currently, this will not show the message div. Once we change the isLoggedIn to true it shows the msg “Hello World!” in our DOM.

v-else

As the name of this directive suggests. This is used to display the content in DOM when the condition given to v-if resolves to false.

For example, we can have a login button if the user is not logged in.

<div v-if="isLoggedIn">{{msg}}</div>
<button v-else> Log In </button>

v-else does not need value as shown above. But it has to come immediately after an element with v-if or v-else-if directive.

v-else-if

This directive can be used when we need to evaluate or show/hide two or multiple DOM elements depending upon different conditions. This will also make sure that only one chained item in the else-if chain is visible.

For example, if the property named isLoggedIn is false, we check for another data property isValid and display a label.

<div v-if="isLoggedIn">{{msg}}</div>
<label v-else-if="isValid">Valid User</label>
<button v-else> Log In </button>

v-show

This conditional directive vue is quite similar to the v-if one. The v-show directive can also be used to show and hide DOM elements based on expressions. But there are a few key differences that are as follows:

  • v-if only ads the DOM element if the condition is met. On the other hand, v-show renders the DOM element but binds the CSS display property with the given condition to the directive.
  • v-show does not support v-else or v-else-if directives.
  • v-show is fast if the elements visibility is switched frequently, however, the v-if has an advantage on the initial render time.

What’s Next

Next, you can learn about vue js v-for here.

Imad

I am a Software Engineer with ample experience in making games, websites, mobile apps and augmented reality solutions.

Pin It on Pinterest