v-if
vs. v-show
Web applications are becoming increasingly dynamic and complex, as is the development process. Long gone are the days when all you needed to whip up a static site were three core web essentials: HTML, CSS, and JavaScript.
Nearly every day, modern frameworks introduce new approaches to developing dynamic web apps. Conditional rendering is a feature shared by all frameworks that has helped developers improve interactivity in their applications.
In this article, we’ll explore the concept of conditional rendering, examine how Vue employs the v-if
and v-show
directives to conditionally render blocks of codes, and highlight their distinctions.
Jump ahead:
v-if
directive used?v-show
directive used?Vue.js v-if
vs. v-show
v-if
and v-show
?In order to fully grasp what’s discussed in this article and the accompanying examples, you should have a fundamental knowledge of Vue.js and its concepts.
Conditional rendering is a core programming concept that is used to create engaging and interactive user interfaces in native and web applications. It allows developers to design more flexible and dynamic components by allowing them to control what content or element is rendered based on certain conditions.
The if
statement is often used for conditional rendering, but modern frameworks offer proprietary directives that provide advanced approaches for conditionally rendering elements to the browser. The Vue.js v-if
and v-show
directives are an example of this.
v-if
directive used?The v-if
directive is equivalent to the if
statement in JavaScript. It is used to conditionally render a block of code. However, unlike the if
statement, v-if
is specific to Vue.js and can only be applied within the template as an element’s directive. Similar to the if
statement, this directive renders the block of code solely if its associated expression evaluates to a truthy value.
To illustrate the functionality of the v-if
directive, let’s imagine a scenario where we want to incorporate a new form into our application but only display it when a particular condition is met, such as when a button is clicked.
First, we’ll create our markup for the form in the template as shown in below code:
<template> <button @click="showForm = !showForm">Show form</button> <div> <form v-if="showForm"> <h1>Test Form</h1> First name:<br /> <input type="text" name="firstname" v-model="firstName" /><br /> Last name:<br /> <input type="text" name="lastname" v-model="lastName" /> <button class="btn">submit</button> </form> </div> </template>
Next, we’ll obtain and store the input box values in their respective states, while simultaneously creating a state variable, showForm
. By default, this variable will be assigned a Boolean value of false
:
<script> export default { name: "app", data() { return { showForm: false, firstName: "", lastName: "", }; }, }; </script>
At this point, the form renders automatically and clicking the show form
button does nothing — despite the fact that we’re using it to toggle the Boolean value of the showForm
state from false
to true
and vice versa on each click:
<button @click="showForm = !showForm">Show form</button>
To dynamically render the form based on the showForm
state condition, we’ll add the v-if
directive to the form
tag and then pass in a Boolean statement, in this case, the showForm
state. If the state’s value is true
, the form will be rendered; otherwise, it will not be rendered:
<form v-if="showForm"> <h1>Test Form</h1> First name:<br /> <input type="text" name="firstname" v-model="firstName" /><br /> Last name:<br /> <input type="text" name="lastname" v-model="lastName" /> <button class="btn">submit</button> </form>
v-show
directive used?The v-show
directive provides an alternative method for conditionally rendering code blocks in Vue. This directive operates in a similar manner to the v-if
directive, rendering a block of code only when the statement provided to it evaluates to a truthy value.
To use the v-show
directive in our form example, we’ll simply replace the v-if
directive with the v-show
directive as shown in the code below:
<form v-show="showForm"> <h1>Test Form</h1> First name:<br /> <input type="text" name="firstname" v-model="firstName" /><br /> Last name:<br /> <input type="text" name="lastname" v-model="lastName" /> <button class="btn">submit</button> </form>
This code will function exactly as it did when the v-if
directive was in use:
v-if
vs. v-show
There isn’t much of a difference between v-if
and v-show
, as you can see from the examples in the previous section. The key difference is that the v-if
directive renders blocks conditionally, while the v-show
directive displays blocks conditionally.
Essentially, this means that the v-if
directive performs complete element re-rendering, while the v-show
directive manages the element’s visibility through CSS properties without affecting its presence in the DOM.
We can observe how this works in real time by checking the behavior of our form using both directives from the browser development tool:
<div> <form v-if="showForm"> <h1>Test Form</h1> First name:<br /> <input type="text" name="firstname" v-model="firstName" /><br /> Last name:<br /> <input type="text" name="lastname" v-model="lastName" /> <button class="btn">submit</button> </form> <form v-show="showForm"> <h1>Test Form</h1> First name:<br /> <input type="text" name="firstname" v-model="firstName" /><br /> Last name:<br /> <input type="text" name="lastname" v-model="lastName" /> <button class="btn">submit</button> </form> </div> </template>
In this code, we duplicated the form and passed the v-if
and v-show
directives to both elements. Toggling the show form
button and inspecting the form in the browser’s development tool yields the same result as demonstrated below:
The first form, as you can see, is fully destroyed and removed from the DOM. The second form remains, but it does not appear in the browser.
An additional characteristic that sets the v-if
directive apart from the v-show
directive is its support for chaining adjacent conditional directives, such as v-else
and v-else-if
, for even more advanced conditional rendering.
We can use these directives to add a bit of interactivity to our application by including a text message that prompts the user to click the show form
button when the form is not currently being displayed. To do so, we’ll modify the template accordingly:
<template> <button @click="showForm = !showForm">Show form</button> <div> <form v-if="showForm"> <h1>Test Form</h1> First name:<br /> <input type="text" name="firstname" v-model="firstName" /><br /> Last name:<br /> <input type="text" name="lastname" v-model="lastName" /> <button class="btn">submit</button> </form> <p v-else>Click the button above to show form</p> </div> </template>
When the form is not being rendered, the v-else
block will display a paragraph tag containing the text: “Click the button above to show form.”
This should give you an idea of how useful the v-if
directive is when it comes to rendering code blocks conditionally.
v-show
and v-if
?You might be curious about the reasoning behind the Vue team’s decision to provide two directives that, although somewhat distinct, essentially serve the same purpose. Well, each of these directives has its own applications, and it is crucial to give thoughtful consideration to which directive to use.
As demonstrated in the previous section, the v-if
directive destroys the rendered elements whenever the condition changes. This can result in a potential performance impact, particularly when the state needs to be toggled frequently. An example of a common use case for this is a modal component that has to be rendered only once during the initial document load.
In contrast, the v-show
directive does not pose a similar issue as it does not destroy and re-render the same block of code when conditions change. However, it does come with a higher initial render cost since it renders its blocks during the initial render, regardless of whether it’s needed. A practical use case is a social share component (or any component, really) that remains hidden when the browser is idle and becomes visible when the user scrolls through the page.
For best results, use the v-if
directive when conditions rarely change during runtime, and opt for the v-show
directive when there is a need for frequent toggling of a conditionally rendered element during runtime.
In this article, we explored conditional rendering and provided an overview of how Vue.js uses the v-if
and v-show
directives to handle conditional rendering. We also examined the differences between these directives with substantial examples, providing a vivid understanding of their workings.
Hopefully, this article will help direct you toward the most appropriate directive for your specific use case. Happy hacking!
Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens in your Vue apps, including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.
The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error and what state the application was in when an issue occurred.
Modernize how you debug your Vue apps — start monitoring for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowCompare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.
It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.
Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.