Welcome back! Last time we went over listening to our very first user events and methods to react to these events. Today you will learn aboutdirectives and conditional rendering.
A simple if-else
One of the most important tools under the belt of any programmer regardless of framework is conditional rendering. The ability to show or hide parts of your app depending on a condition or value is a great place to start learning about this, and also about Vuedirectives.
We will continue building upon our previous example. In case you lost it or are just catching up, here's what we have so far:
<html><head><title>Vue101</title></head><body><h1>Hello!</h1><divid="app"><p>Mylocalproperty:{{myLocalProperty}}</p><hr><button@click="buttonClicked">Clickme</button></div><scriptsrc="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><script>constapp=newVue({el:'#app',data:{myLocalProperty:'Im a local property value'},methods:{buttonClicked(){constnewText='The new value is:'+Math.floor(Math.random()*100);this.myLocalProperty=newText;}}});</script></body></html>
So far we've managed to output our local properties into our app, and also listen to the clicks of a user on a simple button.
Let's take it a step further and learn about our conditional rendering.
Let's change our button clicks so that they generate a random number just as we have been doing, but instead of outputting a concatenated string, we will toggle the display of a couple of<p>
elements with the results.
This will require some refactoring, so first let's change ourbuttonClicked
method to only calculate this new number, and we will store it on a new property calledrandomNumber
.
<script>constapp=newVue({el:'#app',data:{myLocalProperty:'Im a local property value',randomNumber:0// 1},methods:{buttonClicked(){this.randomNumber=Math.floor(Math.random()*100);// 2}}});</script>
Let's take a quick look.
- We've added a new local property
randomNumber
, and the default value will be 0. - We deleted the old code, and instead of using the random value on the previous string we will just store it provisionally in our
randomNumber
prop.
We want to show/hide content depending on the result of ourrandomNumber
calculation, so let's have two new<p>
elements. One will show only whenrandomNumber
is greater or equal to 50. The other will show if it is less than 50.
<divid="app"><p>My local property: {{ myLocalProperty }}</p><hr><button@click="buttonClicked">Click me</button><hr><!-- 1 --><pv-if="randomNumber >= 50">randomNumber is >= 50!</p><!-- 2 --><pv-else>Sorry, randomNumber is only<b>{{ randomNumber }}</b></p></div>
We've added a<hr>
for clary and separation, and then our two<p>
elements.
Let's look at each in detail.
First,v-if="randomNumber >= 50"
. So,v-if
is a Vuedirective. Don't get too caught on the definition of the term, it only means that it is a "special" value that we can place inside HTML elements that Vue will know how read and interpret. In fact, you've already useddirectives before. Rememberv-on:click
and@click
? Those are directives too!
Theory aside,v-if
tells Vue toonly show this element if the condition we declare inside of it istrue. In this case, "Vue: only show this<p>
element IF and only IFrandomNumber
is greater than or equal that 50".
Second, whenever you have av-if
directive, you can have anelse case. But heads up,v-else
ONLY works on an element that directly follows the one that holds thev-if
(or a third optionv-else-if
). As you'd expect from any if - else statement, the element withv-else
will get rendered on any other case that is nottrue for the first. Either/or.
Go ahead and reload yourindex.html
and click the button a few times. You'll see that the<p>
tags get rendered reactively depending on the value ofrandomNumber
.
v-if and v-show
If you're curious to open your dev tools while you click around, you will notice a VERY important thing.v-if
is not adisplay: block/hidden
css switch toggle, it actually renders or destroys elements whenever the value of our conditional changes. If you want to have a visibility toggledirective, go ahead and try switching that firstv-if
forv-show
and see what happens!
You may notice is that the block that has thev-else
declarative is not showing anymore. This is becausev-show
is a lone-ranger and will only work by itself. So what is the benefit of usingv-show
?
There is a performance cost that you may want to consider when usingv-if
because Vue has to go and re-render the DOM (don't worry it's very smart about which parts it needs to add/remove) but this is a more extensive task than applying/removing cssdisplay
properties.
Bottom line: If you're going to toggle a small/medium part of the app a few times only, like a menu bar for example,v-if
will usually do the trick. But if you're going to be switching around tabbed screens for example, or huge chunks of your page thenv-show
may be cheaper in terms of performance because your markup is not getting re-written every time.
(P.S. before we continue, set back the directive tov-if
or else you'll get console errors because of thev-else
below it is unpaired.)
Development tools
If you're wishing you knew a way to figure out which value is getting randomized intorandomNumber
for our>= 50
condition without having to render it inside the<p>
tag with our trusty{{ }}
then Vue has a fantastic tool for the job.
Go ahead and install theChrome Vue Devtools orFirefox Vue Devtools.
Since some of us may be opening the file directly on our browser using thefile://
protocol, if you don't see the extension working for you in chrome. Please first follow these instructions:
"To make it work for pages opened via file:// protocol, you need to check "Allow access to file URLs" for this extension in Chrome's extension management panel."Right-click the Vue icon on the extensions toolbar, click on manage extensions and then toggle the allow access switch.
Once you've added them to your favorite flavor of browser, go ahead and open them (Open your dev tools by "inspecting" or through the browser menus, then navigate to the "Vue" tab on the development pane) while you're on yourindex.html
page and you'll notice quite a few goodies to play around with.
The screen you should see looks like this:
You'll notice a toolbar with some icons on the top right, those we're going to look at when we look atVuex and you can safely ignore them for now.
The important thing in this screen however, is the components tree. The dev tools will allow you to inspect every component that you create for a page, its properties (data) and later on when we look at state management how they interact with it. (Don't worry if this makes no sense right now).
Click on the<Root>
component and you will see this:
Notice our two local properties,myLocalProperty
andrandomNumber
.
Click on your<button>
a few times and see how the developer tool responds by showing you the changes in therandomNumber
value.
Now, this may not seemsuper impressive right now, but this tool will be your #1 source of information when we start building a real world application, or even in your actual work projects, so definitely spend some time playing with it!
A neat thing for example with local storage is that you can modify the values manually to test different states of your application. Hover of the property you want to modify and you'll get an edit button and (in case of numeric properties) a + and - button to increase or decrease the value.
Conclusion
With the fundamentals that we've already covered: setup, events, properties and conditional rendering you now have the building blocks to start creating some really fun and reactive applications. However, this is just barely scratching the surface of the power of Vue and it only gets more fun and interesting from here.
Stay tuned for part 4!
Top comments(9)

- Joined
Hey Fred! :) Thanks for your awesome comment

- Joined
Thanks iPAS! Hope you enjoy the rest of it :)

- LocationBangalore
- EducationPSG college of technology
- WorkSoftware developer at Accenture
- Joined
Cool!

- Joined
Hi. You're right, it should be index.html - good catch :)
For further actions, you may consider blocking this person and/orreporting abuse