Learning Management Platform for Written Tutorial Series.

Vue JS Directives

Vue JS Directives

Introduction

Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell Vue's HTML compiler to attach a specified behaviour to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.

Essentially, a directive is some special token in the markup that tells the library to do something to a DOM element. In Vue.js, the concept of directive is drastically simple. A Vue.js directive can only appear in the form of a prefixed HTML attribute that takes the following format:

<element prefix-directiveId="[arg:] ( keypath | expression ) [filters...]"></element>

By the time that you are done with this tutorial, you will create the following simple app that displays status updates.

VueJS Directives

We will also cover other directives such as

VueJS Directives

Topics to be covered

We will cover the following topics in this course.

  • Tutorial pre-requisites
  • How to use Vue.js directives
  • v-text directive
  • v-html directive
  • v-show directive
  • v-if and v-else Directive
  • v-for

Pre-requisites for learning Vue.JS

For you to successfully complete this tutorial, you must know / have the following

  • Basic understanding of HTML/CSS.
  • Basic understanding of JavaScript.
  • A text editor i.e. Sublime, Brackets etc. for writing code
  • Web server, this is optional but highly recommended. Vue.JS works on the frontend and chances are, you will need something like PHP, Ruby On Rails or ASP on the backend. We will use PHP for these tutorial series.
  • Modern web browser that supports HTML 5 and has JavaScript enabled.
  • Node.js this is optional but highly recommended. Vue has a command line interface CLI that makes development easier. Node.JS is a prerequisite for working vue-cli.
  • Git this too is optional but highly recommended. It’s a prerequisite for vue-cli.

How to use Vue.js directives

Directives in Vue.js are used like attributes on an element. They are represented with a v-* prefix and provide a common functionality throughout the app.

Tutorial project organization

We will work with three files namely;

  • app.js – this will be the JavaScript file that will contain all of the Vue code
  • index.html – this will be used to demonstrative directives such as v-text, v-html etc.
  • updates.html – this will be used with the v-for directive to display user status updates as shown in the image above.

We will be using Bulma CSS framework for styling and Lorempixel for images used in the user status updates.

Create a file index.html

Add the following code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Vue.JS Directives</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.3.1/css/bulma.min.css">
        <style type="text/css">
            body{padding: 40px}
        </style>
        <script src="https://unpkg.com/vue/dist/vue.js"></script>
    </head>
    <body>
        <div class="container" id="app">

        </div>
        <script src="app.js"> </script>
    </body>
</html>

HERE,

  • <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.3.1/css/bulma.min.css"> pulls in Bulma from a cdn network
  • <style type="text/css">…</style> pads the body element with 40px on top, bottom, left and right.
  • <script src="https://unpkg.com/vue/dist/vue.js"></script> pulls in Vue JS from the cdn network
  • <div class="container" id="app"> creates a container div with the id of app. All of our code will be within this container.

v-text Directive

The v-text directive is used to interpolate text. It does the same things as double mustache brackets {{ var }}

Add the following code to the container div that we created in the above section

<article class="message is-info">
    <div class="message-header">
        <p>v-text</p>
    </div>
    <div class="message-body" v-text="message"></div>
</article>

HERE,

  • <div class="message-body" v-text="message"></div> v-text directive interpolates the value of message into the div.

Open app.js and add the following code

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
    }
})

HERE,

  • var app = new Vue({…}) we create an instance of Vue and assign it to the variable app.
  • el: '#app', binds the Vue instance to the container div via the id app
  • message: 'Hello Vue!', defines a variable message and assigns the value Hello Vue! To it.

Open index.html in the web browser

You will get the following results

VueJS v-text

v-html Directive

It does the same job as v-text but it inserts the actual HTML into the DOM. This gives the same results as of innerHtml property in JavaScript. Add the following code just below the article for v-text

<article class="message is-info">
    <div class="message-header">
        <p>v-html</p>
    </div>
    <div class="message-body" v-html="value"></div>
</article>

HERE,

  • <div class="message-body" v-html="value"></div> v-html interpolates the value of the variable value as raw HTML into the div.

Modify the app.js file as follows

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        value:'Welcome to the tutorial <small>which is all about Vue.js</small>',
    }
})

HERE,

  • value:'Welcome to the tutorial <small>which is all about Vue.js</small>', assigns text that contains HTML tag(s) small to the variable value

Open index.html in the web browser

You will get the following results

VueJS v-html

Note: the text which is all about Vue.js is in smaller print compared to the text Welcome to the tutorial

v-show Directive

This is a conditional rendering operator where data is displayed depending upon the value predefined in the Vue's JavaScript object. Add the following code to index.html

<article class="message is-info" v-show="viewed">
    <div class="message-header">
        <p>v-show</p>
    </div>
    <div class="message-body">Do you see me!!</div>
</article>

HERE,

  • <article class="message is-info" v-show="viewed"> v-show imposes a condition on the visibility of the article. If the value of viewed is true, the article is displayed otherwise it is not displayed.

Open app.js and modify it as follows

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        value:'Welcome to the tutorial <small>which is all about Vue.js</small>',
        viewed:true,
    }
})

HERE,

  • viewed:true, defines the variable viewed and initializes it to true

Open index.html in the web browser

You will get the following results

VueJS v-html

In the previous tutorial, we installed Vue devtools. We will now use Vue devtools to play around with the value of viewed and see what happens

Press F12 to open the developer tools in Google chrome

Select the Vue tab

Run the following command in the console

app.viewed = 0

VueJS devtools

The message box v-show will disappear from the web page

Set app.viewed = 1 from the console

The message box v-show will reappear

v-if and v-else Directive

This is again a conditional rendering operator but unlike v-show, which hides the text in he DOM, the v-if Directive doesn't render or removes the data in the DOM. With minor amendments the above example.

Add the following article

<article class="message is-info">
    <div class="message-header">
        <p>v-if...else</p>
    </div>
    <div class="message-body">
        <p v-if="viewed">viewed is true</p>
        <p v-else="viewed">viewed is false</p>
    </div>
</article>

HERE,

  • <p v-if="viewed">viewed is true</p> displays viewed is true if the value of viewed is true
  • <p v-else="viewed">viewed is false</p> is displayed if the condition set in v-if is false.

v-for Directive

It’s a simple and easy to use but a very powerful directive and provides a functionality which is similar to a for-loop using inside a HTML document. This is a widely used directive in real world projects for rendering data from databases where number of objects is unknown. This comes in handy where same code-block needs to be executed many times.

We will use v-for to create a simple app that displays user status updates. Something a bit similar to twitter.

Let’s start with app.js and modify it as follows

var updates = [
            {
                name:'John Doe',
                handle:'johndoe',
                status:'Away on holiday',
                age:'31m',
                avatar:'http://lorempixel.com/64/64/people/',
            },
            {
                name:'Mary Jane',
                handle:'mary-j',
                status:'Rocking Vue.JS Tuts :)',
                age:'10s',
                avatar:'http://lorempixel.com/64/64/sports/'
            },
            {
                name:'Jack Smith',
                handle:'jsmith',
                status:'Cooking dinner for the family',
                age:'2 days',
                avatar:'http://lorempixel.com/64/64/food/'
            },
            {
                name:'Alan Shore',
                handle:'mrshore',
                status:'Oh yeah! black sails.',
                age:'13m',
                avatar:'http://lorempixel.com/64/64/nature/'
            },
        ]

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        value:'Welcome to the tutorial <small>which is all about Vue.js</small>',
        viewed:true,
        updates:updates
    }
})

HERE,

  • var updates = […] defines an array with status updates. This usually comes from the database but for simplicity’s sake we will work with these static values. Using the updates variable, we have defined the name, handle, status, age of the status and the user avatar. We are using image place holders in our example
  • updates:updates adds a new variable to our model updates and assigns the contents of the array variable updates.

Create a new file updates.html and add the following code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Vue.JS Directives</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.3.1/css/bulma.min.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
        <style type="text/css">
        body{padding: 40px}
        </style>
        <script src="https://unpkg.com/vue/dist/vue.js"></script>
    </head>
    <body>
        <div class="container" id="app">
            <h2 class="title">Status Updates</h2>
            <div class="box" v-for='update in updates'>
                <article class="media">
                    <div class="media-left">
                        <figure class="image is-64x64">
                            <img :src="update.avatar" alt="Image">
                        </figure>
                    </div>
                    <div class="media-content">
                        <div class="content">
                            <p>
                                <strong>{{update.name}}</strong> <small>@{{update.handle}}</small> <small>{{update.age}}</small>
                                <br>
                                {{update.status}}
                            </p>
                        </div>
                        <nav class="level">
                            <div class="level-left">
                                <a class="level-item">
                                    <span class="icon is-small"><i class="fa fa-reply"></i></span>
                                </a>
                                <a class="level-item">
                                    <span class="icon is-small"><i class="fa fa-retweet"></i></span>
                                </a>
                                <a class="level-item">
                                    <span class="icon is-small"><i class="fa fa-heart"></i></span>
                                </a>
                            </div>
                        </nav>
                    </div>
                </article>
            </div>
        </div>
        <script src="app.js"> </script>
    </body>
</html>

HERE,

  • <div class="box" v-for='update in updates'> v-for directive loops through the array variable updates and assigns the individual items to the variable update. The entire div with the class box and its contents is displayed as an individual entity with each iteration.
  • <img :src="update.avatar" alt="Image"> uses v-binding to set the img tag src attribute to the one that we retrieve from the avatar variable. It is incorrect to use it as <img src="update.avatar">. It will not work. :src="update.avatar" is the shorthand format of the longer version v-bind:src="update.avatar"
  • {{update.name}} displays the user name
  • {{update.handle}} displays the user handle
  • {{update.age}} displays the age of the status
  • {{update.status}} displays the status

Open updates.html

You will be able to see the following display

VueJS Directives

Depending on our readers’ requests, we may consider fully developing this application using Laravel for the backend.

Summary

In this tutorial, we looked at the directives in Vue.js is, and how to use them using real world practical examples.

What’s next?

The next tutorial will be on Vue JS components.

Kode Blog Tutorials is dedicated to bring you update to date, high quality free tutorials. You can support us by using the social media buttons to like and share the tutorial and subscribing to our newsletter. Please use the comments section below to give us feedback.

You can sign up for a free account on our site and you will be able to keep track of your progress as you go through the tutorial series and get notifications when we publish new content.


...