Getting started with Vue.js - part two - conditional rendering

Getting started with Vue.js - part two - conditional rendering

Published 29. aug 2019 04:47 by Stein Ove Helset

In the second part of the course, we will go through how you render parts of the template based on values in your data object.

Adding some CSS

Since we're not covering how to learn CSS in this course we are just going to include a CSS library called Bulma. It's fantastic to work with and is a good alternative to Bootstrap. Just include this html tag inside your <head>:

<link rel="stylesheet" href="">

Conditional rendering

Often when we build web apps we want to hide or show elements based on something. In Vue we have something called conditional rendering. We can set a element to show if a value is true and if it's not there can also be a fallback element. Here is a short example:
Vue Hero - Introduction - Conditional rendering

The first this we are going to do now is to replace the contents of <div id="hero_app"> with this code.

Vue Hero - Introduction - Conditional rendering two

Next, we need to do is to make a change to the Vue instance.

Vue Hero - Introduction - Vue instance code

Now we have added everything thing we need in order to test the conditional rendering. If you refresh the page in your browser you should see something like this:

Vue Hero - Introduction - Preview 2

As you can see here there is nothing more content than earlier because of the conditional rendering that makes the description block not visible because there is no description. If you add a little bit content to the description variable and refresh the page it will now look like this:

Vue Hero - Introduction - Conditional rendering three

This is just the default card element from Bulma, but it gives us a great opportunity do cover many parts of Vue.

Extra information about conditional rendering

The directive v-if, v-else-if and v-else determines if a block should be rendered or not. If you just want to hide a block of code you can use the v-show directive which just adds a display: none to the element. Here is an example that will hide a block of code instead of preventing it from rendering:

Vue Hero - Introduction - Extra conditional

Summary and mini challenge

In this last part, you learned how to show a block of code based on if a value is true or not. In this challenge I want you to make it possible to show a default description if the description value is empty. If you need help at this I suggest that you read the tip about conditional rendering a little bit further up at this page. This will not be a part of the course so when you're finished you can just remove it.

Share this post


Add comment