Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Difference Between v-if and v-show [With Video at End]

DZone's Guide to

Difference Between v-if and v-show [With Video at End]

In this post, we take a quick look at these two different ways of handling UI elements in the popular Vue.js framework for web app development.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

v-if

The control structure followed by Vue.js for UI element rendering. v-if supports the control branching if..else if..else.

if..else if..else

A quick example to render spans based on the value typed in the input.

<div id="app_div">
<input type="text" v-model="show_type"/>
<span v-if="show_type=='Fruits'">Fruits</span>
<span v-else-if="show_type=='Birds'">Birds</span>
<span v-else>Animals</span>
</div>
<script>
var app = new Vue({
el: "#app_div",
data: {
show_type: 'Birds'
}
});
</script>

It renders the "Fruits" and "Birds" span when I typed "Fruits" and "Birds" in the input text, respectively. Otherwise, it renders the "Animal" span.

v-show

A boolean control to manage the display of a UI element.

<div id="app_div">
<span v-show="show_sky">Sky</span>
</div>
<script>
var app = new Vue({
el: "#app_div",
data: {
show_sky: false
}
});
</script>

As with the "show_sky" variable used in this example, depending on that, it either displays the span or hides it.

v-show vs. v-if

  • Unlike v-ifv-show has no else part.
  • v-if only renders the elements which satisfy the condition. But  v-show renders all elements and manages with CSS "display" attribute.

The following video contains a demonstration of v-ifvs v-show

Hope this helps.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
web dev ,vue.js ,web application development ,ui development

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}