Contact Information

KodeBlog

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

VueJS Templates

Templates are a feature of Vue that allow us to attach the rendered DOM to the Vue instance's data. For example, you can write standard HTML code and assign it to a variable that you define in the data parameter of the Vue instance. You can them use that HTML code to display it in the browser using the Vue directive v-html.

Vue does some processing in the background to compile the templates and renders intelligently so that the process does not affect the user experience negative. In this lesson, we will look at practical examples that demonstrate how to do that.

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-templates

Open the directory vue-templates 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-instance
-index.html

How to Display Plaintext

Let's now look at how you can display plaintext in Vue. We do this by using the double curly brackets {{ variable }}. We will create a simple program that displays a message in the web browser

Open the file index.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>VueJS Instance</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p>{{ message }}</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    message: '<strong>I am</strong> plaintext'
                }
            });
        </script>
    </body>
</html>

HERE,

  • <p>{{ message }}</p> Vue interprets the double curly brackets and outputs the value
  • data: {message: '<strong>I am</strong> plaintext' } defines a variable message that is assigned a string value that purposely contains some HTML elements to make the text bold.

Open the file index.html in the web browser, you should be able to get the following message

<strong>I am</strong> plaintext

As you can see from the above code, the HTML tags have not been interpreted by the browser but instead displayed as plain text.

You should use the double curly brackets {{}} when you want to display just plaintext that does not contain any special codes that you would like the browser to execute

In the next section, we will deal with the issue of HTML code within Vue instance data and how you can render them as HTML

How to Outputting Raw HTML

In this section, we will work with outputting raw HTML. We will define some special HTML code within a data member and render it as such in the web browser. To make things simple, we will just add another paragraph to the above example that will render the message as raw HTML instead of plaintext.

Inside the div with the id of root, just below the code <p>{{ message }}</p> add the following line

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

HERE,

  • <p v-html="message"></p> adds an attribute v-html with the value of message which is the name of the data member with the Vue instance

Reload the page index.html in the web browser

You should be able to get the following results

{{ image place holder }}

As you can see from the above results, the first text is just plaintext with visible HTML code but in the second line, I am is bold because we applied the HTML tag strong on it.

How to Bind HTML Attributes to Data Variables

In this section, we will define Vue instance data that contains a link to a website and see how we can output that in the web browser

Open the file attributes.html then 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>VueJS Bind HTML Attributes</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p>Website: {{ website }}</p>
            <a href="{{link}}">Open {{ website }} link</a>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    website: 'Google',
                    link: 'https://www.google.com/'
                }
            });
        </script>
    </body>
</html>

HERE,

  • data: {...} we define two members website and link which we want to render in our HTML page
  • <p>Website: {{ website }}</p> prints the value of website
  • <a href="{{link}}">Open {{ website }} link</a> creates a link that opens the value of link as specified in the href attribute of the a anchor.

Open the file attributes.html in your web browser and click on the link.

You will not be able to navigate to the website of Google as specified in the value of link.

View the HTML page source and you should be able to see that the value of href is as follows

<a href="{{link}}">Open {{ website }} link</a>

This is because double curly brackets dot not work within attributes of HTML elements. This also applies to attributes like src of the image tag. For you to use Vue instance data within HTML elements, you need to use data binding using the Vue directive v-bind:attribute=value.

Modify the link paragraph like so

<a v-bind:href="link">Open {{ website }} link</a>

HERE,

  • v-bind:href uses the v-bind directive to bind the value of the attribute href to the value of the data member link

Reload the web page in the web browser after saving the above changes made to the file

If you click on the link, you should be able to get to the website for Google.

How to Use JavaScript Expressions

Vue supports the use of JavaScript expressions within templates but they are limited in use. You can use ternary operators, call methods on strings, arrays etc.

Let's create a data member that contains an array of fruits that we will output in the web browser. We will then call the JavaScript sort array method.

Open the file expressions.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>VueJS JavaScript Expressions</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p v-once>Fruits: {{ fruits }}</p>
            <p>Sorted Fruits: {{ fruits.sort() }}</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    fruits: [
                        'Oranges',
                        'Apples',
                        'Mangoes',
                        'Tomatoes',
                        'Bananas'
                    ]
                }
            });
        </script>
    </body>
</html>

HERE,

  • <p v-once>Fruits: {{ fruits }}</p> applies the v-once directive to the paragraph so that we only print the value of fruits once and not update it when the underlying data has been modified
  • <p>Sorted Fruits: {{ fruits.sort() }}</p> calls the sort method on the fruits array object to sort its contents then prints the value in the browser

Open the file expressions.html in the web browser

You should be able to see the following results

Fruits: [ "Oranges", "Apples", "Mangoes", "Tomatoes", "Bananas" ]

Sorted Fruits: [ "Apples", "Bananas", "Mangoes", "Oranges", "Tomatoes" ]

As you can see, the first array has the fruits in their original positions

The second list has been sorted alphabetically.

Vue allows you to work with JavaScript expressions in templates when rendering data. The following examples demonstrate different types of expressions

<P>{{ 1 + 1 }}</P>
<p>{{ 1 == 1 ? 'TRUE' : 'FALSE' }}</p>

HERE,

  • <P>{{ 1 + 1 }}</P> evaluates an arithmetic operation and returns the result in the browser
  • <p>{{ 1 == 1 ? 'TRUE' : 'FALSE' }}</p> checks if 1 == 1 which if true will out TRUE and if false will output FALSE.

Summary

Vue templates allow us to bind the DOM to Vue instance data that we can output as raw HTML. The HTML valid code can be defined in a data member then used to create the output in the DOM using the v-html directive. Double curly brackets {{}} are used to output plaintext. HTML element attributes can be linked to data members using the v-bind directive. Vue also allows the use of JavaScript expressions within templates.

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.

VueJS Instances

VueJS Computed Properties

Leave A Reply