Vue.js is an easy to learn and approachable library that we can start building web applications in it with the basic knowledge of web development. In Vue.js, developers love to code and feel freedom while developing applications.
In any dynamic web application, conditional rendering is a necessary part. Vue.js provides different ways for conditional rendering, and we can use any of the following ways which suit our purpose:
- v-show
- v-if
- v-else
In this article, we will try these directives provided by Vue.js for conditional rendering and understand them in a better way.
v-show
The v-show only hides the element by disabling its visibility. It hides the element if the value of the passed expression or variable is not truthy.
For example:
v-if
On the other hand, v-if does not hide the element, but it also does not render anything until the value of the passed expression or variable becomes true.
For Example:
There is an additional feature in the v-if directive as compared to the v-show directive. We can apply it to the template block as well if we do not want to render anything in between that block. Either there is a child component in that or a lot of other elements.
For example:
v-else
We can also use the v-else directive along with the v-if statement in order to conditionally render between any of the two blocks. But, keeping in mind that the v-else block must have to appear right after the v-if block.
For example:
We can apply v-else on the template block as well.
v-else-if
Just like v-else, we can also use the v-else-if directive along with the v-if directive.
For example:
v-if vs. v-show
The v-if and v-show kind of do the same task. They both hide the elements in the DOM based on the truthy or falsy value of the passed expression, but with a subtle difference of hiding and not rendering elements.
If we compare the time and processing cost between these two. The v-if costs more during runtime or toggling, while v-show costs more at the start of rendering. So, it would be wise to use v-show when toggling is purpose. Otherwise, v-if is preferred.
Wrapping up
In this article, we have learned how to conditionally render the DOM in Vue.js using v-if and v-else directives. We have shown some examples and learned about the real difference between v-show and v-if directive. If this article helps you to have a better understanding and concepts, keep on visiting linuxhint.com for such useful content.