Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 828 of the free egghead.io lessons, plus get JavaScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Just one more step!

Check your inbox for an email from us and click link to unlock your lesson.



Conditionally Render DOM Elements in Vue.js

1:01 JavaScript lesson by

You can use v-if and v-else to display content based on assertions on your data. Similarly, v-show can be used to render the content, but hide it with css. v-if can also be used on an invisible wrapper <template> element.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

You can use v-if and v-else to display content based on assertions on your data. Similarly, v-show can be used to render the content, but hide it with css. v-if can also be used on an invisible wrapper <template> element.

Avatar
marushkevych

removeItem is invalid - it passes the event to splice, so it always deletes first item

Here's a list of Dinosaurs. Let's prevent the heading from rendering, if there's no list. We'll add v-if, and set that to the comparison, ="dinos.length > 0".

Now, our heading will be hidden if there are no Dinosaurs. That leaves the markup for the list. Let's create a new element called "template," and move our v-if statement onto it.

The element template won't be rendered in the view, but everything inside it will now be conditionally rendered. If there isn't a list, we want to show a message.

Let's create a paragraph tag with v-else, and give it some text. A v-else element will be rendered, if the previous v-if wasn't.

Now, we want to conditionally show the addition and subtraction button, based on the quantity of that species. For the addition button, let's add v-show, and set it equal to "dino.quantity < 5".

For the subtraction, we'll set v-show= "dino.quantity > 1". v-show allows the element to be rendered in the view, and to be shown, or hidden with CSS.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?