Vue JS Basics (Questions/Answers) : Abhishek Chaturvedi
How to create an instance in Vue?
In VueJS, the application starts by creating a new Vue instance with this function :
var vm = new Vue({
//some code or options
})
The standard way to follow is to use the variable vm which is donated as ViewModel from which we can refer our Vue instance.
Let me example this via a basic example to better 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 = "app">
<h1>Name : {{name}}</h1>
<h1>Age : {{20}}</h1>
<h1>{{info()}}</h1>
</div>
<script type = "text/javascript" src = "js/vue_instance.js"></script>
</body>
</html>
And the vue_instance.js will look like :
var vm = new Vue({
el: '#app',
data: {
name : "Abhishek Chaturvedi",
age : 20
},
methods: {
info : function() {
return "Hello, My name is "+this.name +" and my age is "+ this.age;
}
}
})
el is a parameter in Vue which takes the id of the DOM element. In our example, we have -”app”.
In our Vue instance we’ve defined the data object and methods. Which we are using in the html to display the data using interpolation.
The interpolation here is donated by {{}}.
And the output will be: