We now have a youtube channel. Subscribe!

Vue.js | Instances

Vue.js Instances


Hello folks! welcome back to a new edition of our Vue.js tutorial. In this tutorial, we will be studying about Vue.js Instances.

To start with Vue.js, we need to create the instance Vue, which is called the root Vue Instance.

Syntax

The following below is the syntax to create Vue.js instance -

var app = new Vue({
   // options
})

Let us treat an example to understand what needs to be part of the Vue constructor.

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "vue_det">
         <h1>Firstname : {{firstname}}</h1>
         <h1>Lastname : {{lastname}}</h1>
         <h1>{{mydetails()}}</h1>
      </div>
      <script type = "text/javascript" src = "js/vue_instance.js"></script>
   </body>
</html>

vue_instance.js.

var  vm = new Vue({
   el: '#vue_det',
   data: {
      firstname : "Kennedy",
      lastname  : "Nkpara",
      address    : "Texas"
   },
   methods: {
      mydetails : function() {
         return "I am "+this.firstname +" "+ this.lastname;
      }
   }
})

For Vue, there's a parameter which is called el. It takes the id of the DOM element. In the above example, we have the id #vue_det. It's the id of the div element, which is present in .html file.

<div id = "vue_det"></div>

Now, whatever we will do will affect the div element and nothing outside it.

Now, we have defined the data object. It has value firstname, lastname, and address.

Same is assigned in the div. For example.

<div id = "vue_det">
   <h1>Firstname : {{firstname}}</h1>
   <h1>Lastname : {{lastname}}</h1>
</div>

The Firstname: {{firstname}} value is going to be replaced inside the interpolation, that is {{}} with the value that is assigned in the data object, i.e Kennedy. The same goes for lastname.

Next, we've methods where we have defined a function mydetails and a returning value. It is assigned inside the div as.

<h1>{{mydetails()}}</h1>

Hence, inside {{} } the function mydetails is called. The value that is returned in the Vue instance will be printed inside {{}}.

Output

Below is the output of the above example -



Now, we need to pass options to the Vue.js constructor which is mainly data, callbacks, template, element to mount, methods, etc.

Let's take a look at the options to be passed to the Vue.

#data

This data can be an object or a function. Vue converts its properties to getters/setters to make it reactive.

Let us take a look at how the data is passed in the options.

Example

Following is a simple example -

<html>
   <head>
      <title>VueJs Introduction</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <script type = "text/javascript">
         var _obj = { fname: "Kennedy", lname: "Nkpara"}
         
         // direct instance creation
         var vm = new Vue({
            data: _obj
         });
         console.log(vm.fname);
         console.log(vm.$data);
         console.log(vm.$data.fname);
      </script>
   </body>
</html>

Output

Below is the output of the above example -


console.log(vm.fname); // prints Kennedy.

console.log(vm.$data); // prints the full object as shown above

console.log(vm.$data.fname); // prints Kennedy

If there is a component, the data object has to be referred from a function as illustrated in the following code -

<html>
   <head>
      <title>VueJs Introduction</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <script type = "text/javascript">
         var _obj = { fname: "Kennedy", lname: "Singh"};
         
         // direct instance creation
         var vm = new Vue({
            data: _obj
         });
         console.log(vm.fname);
         console.log(vm.$data);
         console.log(vm.$data.fname);
         
         // must use function when in Vue.extend()
         var Component = Vue.extend({
            data: function () {
               return _obj
            }
         });
         var myComponentInstance = new Component();
         console.log(myComponentInstance.lname);
         console.log(myComponentInstance.$data);
      </script>
   </body>
</html>

in case of a component, the data given is a function, which is used with Vue.extend as shown above. The given data is a function. For example -

data: function () {
   return _obj
}

To refer to the data from the component, we need to create an instance for it. Below is a short example -

var myComponentInstance = new Component();

To fetch the details from the data, we must perform the same as we did with the parent component above. For example -

console.log(myComponentInstance.lname);
console.log(myComponentInstance.$data);

Following are the details shown in the web browser -



Props

Data type for props is an array of strings or object. It takes an array-based or an object-based syntax. They are said to be attributes that are used to accept data from the parent component.

Example 1

Following is a simple example -

Vue.component('props-demo-simple', {
   props: ['size', 'myMessage']
})

Example 2

Following is a simple example -

Vue.component('props-demo-advanced', {
   props: {
      // just type check
      height: Number,
      
      // type check plus other validations
      age: {
         type: Number,
         default: 0,
         required: true,
         validator: function (value) {
            return value >= 0
         }
      }
   }
})

propsData

This is used for unit testing.

Type

Array of strings. For example, { [key: string]: any }. It needs to be passed during the Vue instance creation.

Example

Following is a simple example -

var Comp = Vue.extend({
   props: ['msg'],
   template: '<div>{{ msg }}</div>'
})
var vm = new Comp({
   propsData: {
      msg: 'hello'
   }
})

Computed

Computed - Type: { [key: string]: Function | { get: Function, set: Function }}.

Example

Following is a simple example -

<html>
   <head>
      <title>VueJs Introduction</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <script type = "text/javascript">
         var vm = new Vue({
            data: { a: 2 },
            computed: {
            
               // get only, just need a function
               aSum: function () {
                  return this.a + 2;
               },
               
               // both get and set
               aSquare: {
                  get: function () {
                     return this.a*this.a;
                  },
                  set: function (v) {
                     this.a = v*2;
                  }
               }
            }
         })
         console.log(vm.aSquare);  // -> 4
         vm.aSquare = 3;
         console.log(vm.a);       // -> 6
         console.log(vm.aSum); // -> 8
      </script>
   </body>
</html>

Computed has two options which are aSum and aSquare.

Function aSum returns this.a+2. Function aSquare again has two functions get and set.

Variable vm is an instance of vue and it calls aSquare and aSum. In addition vm.aSquare = 3 calls the set function from aSquare and vm.aSquare calls the get function.

Output

We can check the result in the web browser which looks like the below screenshot -


Methods

Methods are to be added with Vue instance as shown in the below code. We can access the function using the Vue object.

<html>
   <head>
      <title>VueJs Introduction</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <script type = "text/javascript">
         var vm = new Vue({
            data: { a: 5 },
            methods: {
               asquare: function () {
                  this.a *= this.a;
               }
            }
         })
         vm.asquare();
         console.log(vm.a); // 25
      </script>
   </body>
</html>

Methods are part of Vue constructor. Let us make a call to the method via the Vue object vm.aSquare (), the value of the property a is updated in the aSquare function. The value of a is changed from 1 - 25, and the same is reflected in the following browser console.



Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we will be discussing about Vue.js Template.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2022 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain