Contact Information

KodeBlog

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

VueJS Instances

Every Vue application must create an instance of the object Vue. The instance variable that we create has a global scope and allows us to specify the elements that we want to work with, what data should be available to the application, define methods that should be responding to events such as when a user clicks a button etc.

In this lesson, you will know everything that you need to know about the Vue instance and work with practical examples.

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

Open the directory vue-instance 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
  • person.html - example application
  • methods.html example application
  • hooks.html example application

The following visualizes our project setup

vue-instance
-index.html
-person.html
-methods.html
-hooks.html

 

How to create a Vue instance

In this section, we will look at how to declare an instance variable of Vue. The syntax is the same as declaring any JavaScript variable except we initialize the variable to an object of Vue.

The following variable initializes the variable vm to an instance of Vue

let vm = new Vue({
    //options
})

HERE,

  • vm declares a variable vm that is initialized to an instance of the object Vue. The name vm is the conventional and commonly used name. You can use any name that you want but for the sake of conventions its better to stick with vm.
  • //option - the initialization accepts a number of parameters such as el,data,methods etc.

Vue Hello World

Let's now create our first Vue application. We will create the traditional Hello World application. We will basically print the message Hello World using Vue 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>Vue Hello World</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: 'Vue Hello World'
                }
            });
        </script>
    </body>
</html>

HERE,

  • <html>...</html> defines a standard HTML document with all the necessary elements to have a valid web page
  • <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> loads the JavaScript file for Vue from a content delivery network CDN
  • <div id="root">...</div> defines a div element that has an id value of root. This element will be attached to the view instance and make everything within it available to Vue
  • <p>{{ message }}</p> the double curly brackets {{...}} are used to display variable values in Vue. In this case, we want to display the value of the variable message
  • <script type="text/javascript">...</script> defines a standard script that we will use to our our JavaScript Vue code
  • let vm = new Vue({...}); defines a variable vm that is initialized to an instance of the object Vue
  • el: '#root', attaches the value #root to the object property el. The property el is used to tell Vue which element on the page we want to manipulate
  • data: { message: 'Vue Hello World' } defines a data object that contains a property message. The data object is used to define variables that we want to work with in our application.

You can now open the file index.html in the web browser

You should be able to get the following results

Vue Hello World

Instance Data

We briefly touched on data in the above section. In this section, we will work with more examples that demonstrate how to work with the data object. We will create a simple application that gets the first and last name of a user then prints the results in the web browser

Open the file person.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 Hello World</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p>First Name: {{ first_name }}</p>
            <p>Last Name: {{ last_name }}</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    first_name: 'John',
                    last_name: 'Smith'
                }
            });
        </script>
    </body>
</html>

HERE,

  • The above code is not very different from the Hello World example except it contains two variables.

Open the file person.html in the web browser

You should be able to get the following results

First Name: John

Last Name: Smith

Now open the developer tools in the web browser. You should be able to see something similar to the following

{{ image place holder }}

In the Vue code, we create a variable vm. We will now access that variable and print the contents in the console like so

console.log(vm);

Press enter or return key to execute the code. You should be able to get results similar to the following

{{ image placeholder }}

You can also manipulate the value of the data variables from within the browser terminal like so

vm.first_name = 'Jane'

HERE,

  • vm.first_name = 'Jane' assigns the value Jane to the variable first_name.

Press enter on the keyboard and you should be able to see the name in the browser change from John to Jane

You can also access the variables via the data object like so

vm.$data.last_name = 'Doe'

HERE,

  • vm.$data.last_name = 'Doe' accessed the data object using vm.$data. If you skip the $ sign then you will not be able to access the data object.

If you press enter key then the last name value should change from Smith to Doe. The common conversion is to use vm.data_variable_name instead of using vm.$data.data_variable_name.

Instance Methods

So far, we have only worked with data object. Let's now look at how we can define methods in Vue. We will create a simple function that prints a message Hello World in the browser

Open the file methods.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>Instance Methods</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p>{{ greet() }}</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                methods: {
                    greet : function(){
                        return 'Vue Hello World'
                    }
                }
            });
        </script>
    </body>
</html>

HERE,

  • methods: {...} the methods parameter is used to define all methods that you want to access within the Vue Instance
  • <p>{{ greet() }}</p> calls our function greet. Notice how we have the open and closing brackets at the end of the function name. If you leave the () out then Vue will treat greet as a variable and not a function.

Open the file methods.html in your web browser.

You should be able to get the following result

Vue Hello World

Let's now modify our example and make our function accept a parameter. We will make it accept the parameter name so that we can greet a person instead of the world.

Modify the Vue code in the above example as follows

let vm  = new Vue({
    el: '#root',
    methods: {
        greet : function(name){
            return 'Hello ' + name
        }
    }
});

HERE,

  • greet : function(name){...} our function greet now accepts a parameter name
  • return 'Hello ' + name returns a concatenated message of Helloand the value of the variable name

You can now modify the HTML code calling our function like so

<p>{{ greet('Fiona') }}</p>

HERE,

  • <p>{{ greet('Fiona') }}</p> calls our function greet with the argument Fiona

Refreshing the page methods.html in the web browser produces the following results

Hello Fiona

Accessing view instance data within methods

We will now work with the persons.html example and add a method to it that will concatenate the first and last names then display the result.

Open persons.html and modify the code as follows

<!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>Instance Data</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p>Your name is: {{ sayMyName() }}</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    first_name: 'John',
                    last_name: 'Smith'
                },
                methods : {
                    sayMyName: function(){
                        return this.first_name + ' ' + this.last_name
                    }
                }
            });
        </script>
    </body>
</html>

HERE,

  • sayMyName: function(){...} defines a function sayMyName within the methods object
  • return this.first_name + ' ' + this.last_name uses this keyword to refer to the instance of Vue that we are working with. this.first_name access the first name and this.last_name accesses the last name.
  • <p>Your name is: {{ sayMyName() }}</p> calls the function sayMyName

Loading the file persons.html in the browser should display the following results

Your name is: John Smith

Instance Lifecycle Hooks

The initialization of an instance goes through a number of steps. Hooks allow us to tap into these stages as they occur so that we can do something if we want to. The following are the stages that the instance lifecycle goes through

  • Setting up data observation
  • Compiling the templates
  • Mounting the instance to the DOM
  • Updating the DOM when data changes

Hooks are functions that allow us to add business logic to the various stages of the instance lifecycle. The Vue instance has the following hooks

  • created - this function is called when the instance has been created
  • mounted - this function is executed when the instance has been mounted to the DOM
  • updated - this function is executed when the DOM has been updated
  • destroyed - this function is called when the Vue instance has been destroyed.

Let's now look at a practical example that demonstrates how to work with the hooks described above

Open the file hooks.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>{{ app }}</p>
            <p>{{ version }}</p>
            <p>{{ appDetails() }}</p>
        </div>
        <script type="text/javascript">
            let data = {
                app: 'Usafiri',
                version: '3.3'
            };

            let methods = {
                appDetails : function() {
                    return `You are running ${this.app} version ${this.version}`;
                }
            };

            let vm  = new Vue({
                el: '#root',
                data: data,
                methods: methods,
                created: function(){
                    console.log('Created hook executed at point blank');
                },
                mounted: function () {
                    this.$nextTick(function () {
                        console.log(`The element has been mounted successfully`);
                    })
                },
                updated: function () {
                    //vm.app = 'Shipping'
                    this.$nextTick(function () {
                        console.log(`Vitual DOM has be re-rendered due to data change`);
                    })
                },
                destroyed: function(){
                    //vm.$destroy();
                    console.log('The vm instance has been destroyed at point blank');
                }
            });
        </script>
    </body>
</html>

HERE,

  • created: function(){...} defines the function for the hook created. Our function simply prints something on the console to make it simple
  • mounted: function () {...} defines the function for the hook mounted. Notice how we are using this.$nextTick inside the mounted function. This function is used to defer the executing of the code until the DOM has been rendered
  • updated: function () {...} defines the function for the hook updated. Just like we did with mounted, the updated hook also uses this.$nextTick
  • destroyed: function(){...} defines the hook function that should be called when the instance of Vue has been destroyed.

Open the file hooks.html in the browser then open the developer tools window

You should be able to see the following messages

Created hook executed at point blank
The element has been mounted successfully

The created and mounted hook functions are always executed because these stages are mandatory.

We will now update the data using the console in the browser like so

vm.app = 'Shipping'

Press enter key

You should be able to see the page change the application name to Shipping and the following message should be logged in the console

Vitual DOM has be re-rendered due to data change

The above message is displayed by the hook function updated

We will now use the web browser to kill off the instance of Vue so that the destroyed hook can be executed

Run the following command in the browser console

vm.$destroy();

HERE,

  • the built-in method destroy() is used to destroy the instance of Vue

You should be able to get the following message in the console

The vm instance has been destroyed at point blank

Other Instance Initialization Options

The above options are not the only ones that we can pass in to our Vue instance during instantiation. We have other options such as props, computed etc. We will cover more options and explain them in detail as we proceed with the tutorial series.

Summary

The Vue instance is a global variable that has been initialized to an instance of the object Vue. The common convention is to use vm as the variable name. During the initialization phase, we pass in a number of objects such as the element in the DOM that we wish to manipulate, the data that should be available to the application and methods which should respond to events etc.

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 Directives

VueJS Templates

Leave A Reply