Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

Vue JS Directives

Directives are special markers on DOM elements that enhance functionality. For example, you can use the directive v-html to dynamically inject HTML code into an element.

Directives are very similar to HTML element attributes. For example, when working with the anchor element <a href="#">Hit Me</a>, href is an attribute. We can inject a directive into it like so <a href="#" v-on="showModal">Hit Me</a> where v-on is a directive that attaches the click event to out anchor.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - this is mainly needed for development purposes only. You need NPM which comes with Node to work with tools like Vue CLI
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.
  • HTML & CSS Basics - this is an added advantage. Vue works on the HTML elements to manipulate them. The styling is done using CSS so you must be familiar with the basics

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called vue-components

Open the directory vue-components in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • index.html - this is the file that will contain our application source code

The following visualizes our project setup

vue-components
-index.html

How to use Vue.js directives

Directives in Vue.js are used like attributes on an element. Vue directives start with the prefix v-* followed by the directive name. The following example shows how to use the v-text directive to output the value of a variable message.

<p v-text="message"></p>

HERE,

  • v-text is the directive

Vue v-text Directive

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

Open the file text.html and add the following code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue Events</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p v-text="message"></p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    message: 'Hello Directive'
                }
            });
        </script>
    </body>
</html>

HERE,

  • <p v-text="message"></p> uses the v-text directive to inject plain text in the paragraph element. The directive displays the value of message.
  • data: {...} defines a data member message.

Open the file index.html in the web browser

You should be able to get the following message

Hello Directive

Vue 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. Open the file html.html and add the following code to it.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue Events</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <div v-html="message"></div>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    message: `
                    <h2>Vue rocks</h2>
                    <p>Men directives in Vue are cool</p>
                    <hr>
                    `
                }
            });
        </script>
    </body>
</html>

HERE,

  • <div v-html="message"></div> uses the v-html directive to out the value of message as raw HTML.
  • message:... defines a variable that contains valid HTML code

Open the file html.html in the web browser

You should be able to get the following code

{{image place holder}}

Vue v-show Directive

This is a conditional rendering operator where data is displayed depending upon the value predefined in the Vue's JavaScript object.

Open the file show.htmland add the following code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue Show Directive</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <div v-show="visible">
                <p>You can only see me if visible is true</p>
            </div>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    visible: true
                }
            });
        </script>
    </body>
</html>

Open the file show.html in the browser

You should be able to see the following results

{{image place holder}}

Open the console in the dev tools and run the following command

vm.visible = false

The text in the web browser should disappear

Vue 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.

Open the file if.html and add the following code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue If Else Directive</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p v-if="visible">visible is true</p>
            <p v-else="visible">visible is false</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    visible: true
                }
            });
        </script>
    </body>
</html>

HERE,

  • <p v-if="visible">visible is true</p> displays the paragraph text only if the value of visible is true.
  • <p v-else="visible">visible is false</p>this paragraph is only displayed if the condition set in the v-if directive is false.

Open the file if.html in the web browser

You should be able to see the following results

visible is true

Now open the console in dev tools and run the following command

vm.visible = false

You should be able to see the text that we defined in the v-else directive like so

visible is false

Vue v-for Directive

The v-for directive is used to loop through a collection of items and displaying them in a list. You can use it when you receive data from an API or read directly from the database. We will create a simple application that loops through an array of objects and display the results in the browser.

Open the file for.html and add the following code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue For Directive</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <h4>Fruits listing</h4>
            <ul>
                <li v-for="fruit in fruits">{{fruit.name}}</li>
            </ul>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    fruits: [
                        { id: 1, name: 'Bananas' },
                        { id: 2, name: 'Apples' },
                        { id: 3, name: 'Mangoes' },
                        { id: 4, name: 'Peaches' },
                        { id: 5, name: 'Pineapples' }
                    ]
                }
            });
        </script>
    </body>
</html>

HERE,

  • <li v-for="fruit in fruits">{{fruit.name}}</li> the directive v-for loops through the array fruits and assigns the iteration item to the variable fruit. The code {{fruit.name}} displays the name property of the iteration item
  • fruits: [...] defines an array with fruit objects in it. This data could be coming from an API.

Open the file for.html in the web browser

You should be able to get the following results

{{image placeholder}}

Summary

Directives are special markers on DOM elements that perform specific tasks. Directives can be used to display plain text, raw HTML code, attaches events to elements etc. All built-in directives in Vue start with the prefix v-* followed by the name of the directive. Directives are used like regular HTML attributes on elements.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

Vue JS Components

Leave A Reply