- 4 years ago
- Zaid Bin Khalid
- 5,368 Views
-
2
In this session, we will learn about what is root Vue instance with the help of example and code.
VueJS (Instances)
To get start with VueJS, we need to create the instance of Vue first, which is also known as the root Vue instance.
VueJS (Instances Syntax)
var app = new Vue({
// options
})
To understand it easily let us have a look at an example given below.
Vue (instance.Js)
<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 : "Ria",
lastname : "Singh",
address : "Mumbai"
},
methods: {
mydetails : function() {
return "I am "+this.firstname +" "+ this.lastname;
}
}
})
We have the id called #vue_det in the above example. It is the div element id, which is present in html. there is a parameter for Vue called el.
As you can see the below example It takes the id of the DOM element.
<div id = "vue_det"></div>
First, it will do nothing outside whatever we are doing and it will only affect the div element only.
Secondly, the data object is defined which contain value like firstname, lastname, and address.
Inside the div element the same thing is assigned.
<div id = "vue_det">
<h1>Firstname : {{firstname}}</h1>
<h1>Lastname : {{lastname}}</h1>
</div>
The Firstname: Inside the interpolation value first name value {{firstname}} will be changed.
For example let’s assume a name called Ria. The same goes for last name. The value assigned in the data object with {{}}.
Secondly, we have methods that will assigned inside the div as where we have defined a function mydetails and a returning value.
Now, The function mydetails is called inside {{} }. In the Vue instance the value returned will be printed inside {{}}.
For reference check the output as shown below:
Output
Now, we need to pass options to the Vue constructor which is depend on mainly data, template, elements (mount on), methods, callbacks and etc.
Now have a look at the options to be passed to the Vue.
#data this can be an object or a function it is a type of data that converts Vue i properties to getters or setters to make it reactive.
To understand it easily let’s have a look at how the data is passed in the options.
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: "Raj", lname: "Singh"}
// 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
- 4 years ago
- Zaid Bin Khalid
- 5,368 Views
-
2