In this tutorial, we will see how to use Vue.js Conditional Directives. You can also check out other Vue.js tutorials as listed below
Other Vue.js tutorials
Most of the dynamic web application expects an ability to show or hide elements based on conditions in any front-end framework. Vue.js provides us a set of conditional directives to achieve this effect. These Vue.js conditional directives are v-if
, v-else
, v-else-if
and v-show
.
Once you have created the Vue.js Hello World application, we will extend the same Hello World application to show the Vue.js conditional directive example. In this conditional directive example, we will use the values from the JavaScript data object to conditionally control the view. For example, we’ll see how to use the below given simple data object.
v-if
and v-else
directives
The vue.js v-if directive adds or removes the DOM elements based on the evaluation of given expressions. Using v-if
directive, let’s say we would like to show a welcome message to users if they are logged-in or show them a login form if they are not logged-in.
v-else
directive is used to display content only when the expression in adjacent v-if resolves to false.
Below is the example of v-if
and v-else
directives
In the above code, if you make isLoggedIn: false
, you will see the login components of html.
v-show
directive
v-show
is pretty much same as v-if
directive except the difference in the way they both render the html component. v-show
will always render the content regardless of the truthness of the expression value whereas v-if
will only render the content if the expression is true. Each time the evaluation of the expression toggles between true and false, v-if
will completely destroy and reconstruct the element whereas v-show
will simply toggle the CSS display property of that element to show and hide it.
Although these differences may not seem significant to you at this moment, but they are worth keeping in mind when evaluating performance for larger applications you develop.
Below is the example of v-show
and v-else
directives