Hands-on Vue.js for Beginners (Part 3)
Tags: javascript, beginners, tutorial, vue
Published: 2019-02-09 00:14:54

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 about **directives** 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 Vue **directives**.

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:

```js
<html>
    <head>
        <title>Vue 101</title>
    </head>

    <body>
        <h1>Hello!</h1>
        <div id="app">
          <p>My local property: {{ myLocalProperty }}</p>
          <hr>
          <button @click="buttonClicked">Click me</button>
        </div>

        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        
        <script>
          const app = new Vue({
            el: '#app',
            data: {
              myLocalProperty: 'Im a local property value'
            },
            methods: {
              buttonClicked() {
                const newText = '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 our `buttonClicked` method to only calculate this new number, and we will store it on a new property called `randomNumber`.

```js
<script>
  const app = new Vue({
    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.
1. We've added a new local property `randomNumber`, and the default value will be 0.
2. 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 our `randomNumber` calculation, so let's have two new `<p>` elements. One will show only when `randomNumber` is greater or equal to 50. The other will show if it is less than 50.

```html
<div id="app">
  <p>My local property: {{ myLocalProperty }}</p>
  <hr>
  <button @click="buttonClicked">Click me</button>
  <hr>
  <!-- 1 -->
  <p v-if="randomNumber >= 50">randomNumber is >= 50!</p>

  <!-- 2 -->
  <p v-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 Vue **directive**. 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 used **directives** before. Remember `v-on:click` and `@click`? Those are directives too!

Theory aside, `v-if` tells Vue to **only** show this element if the condition we declare inside of it is **true**. In this case, "Vue: only show this `<p>` element IF and only IF `randomNumber` is greater than or equal that 50".

Second, whenever you have a `v-if` directive, you can have an **else** case. But heads up, `v-else` **ONLY** works on an element that directly follows the one that holds the `v-if` (or a third option `v-else-if`). As you'd expect from any if - else statement, the element with `v-else` will get rendered on any other case that is not **true** for the first. Either/or.

Go ahead and reload your `index.html` and click the button a few times. You'll see that the `<p>` tags get rendered reactively depending on the value of `randomNumber`.

# 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 a `display: 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 toggle **directive**, go ahead and try switching that first `v-if` for `v-show` and see what happens!

You may notice is that the block that has the `v-else` **declarative** is not showing anymore. This is because `v-show` is a lone-ranger and will only work by itself. So what is the benefit of using `v-show`?

There is a performance cost that you may want to consider when using `v-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 css `display` 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 then `v-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 to `v-if` or else you'll get console errors because of the `v-else` below it is unpaired.)

# Development tools

If you're wishing you knew a way to figure out which value is getting randomized into `randomNumber` 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 the [Chrome Vue Devtools](https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en) or [Firefox Vue Devtools](https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/).

Since some of us may be opening the file directly on our browser using the `file://` 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 your `index.html` page and you'll notice quite a few goodies to play around with.

The screen you should see looks like this:
![](https://thepracticaldev.s3.amazonaws.com/i/y259bn17x0ocdxk8p5yg.png)

You'll notice a toolbar with some icons on the top right, those we're going to look at when we look at **Vuex** 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:

![](https://thepracticaldev.s3.amazonaws.com/i/6iiipk8xvm5amsfl3090.png)

Notice our two local properties, `myLocalProperty` and `randomNumber`.
Click on your `<button>` a few times and see how the developer tool responds by showing you the changes in the `randomNumber` value.

![](https://thepracticaldev.s3.amazonaws.com/i/okttb4bc6qiblkin2cjt.png)

Now, this may not seem _super 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.

![](https://thepracticaldev.s3.amazonaws.com/i/jiyj1v122ghzmeya7to1.png)

# 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!