Instances in Vue JS

In this tutorial, we will learn about Vue Instances. And why it is the main part of creating any Vue application.

Instances:

  • Vue Instances are the root of the Vue application.
  • We can think of Vue Instances as a heart that powers our application.

Syntax:

var app = new Vue({ //options})
  • It is created by passing options object into it, which provides optional properties that are used to store data and perform actions.
  • In order to form a relationship between Vue Instances and part of the DOM, we use the property el.

HTML (index.html)

	<div id=”app”>
	<h1> {{ places }} </h1>

JS (vueinstance.js)

var app = new Vue({
	el: '#app',
     data: {
		places: ‘Leh & Ladakh’
	}
});

We will include js file at the end of index.html file i.e

<script src = “vueinstance.js”></script> 
  • Here we are specifying that we’d like to plug instance into the div with the id of the app. Now this div and the content within it is hooked up to our instance.
  • The instance can also have a property for data.

Here we are giving our instance a place, whose value is Leh & Ladakh. In order to display places, we’re using double curly braces {{ }}. The value return by the Vue instances will be printed inside this {{ }}.

This double curly braces {{ }} syntax is called an Expression. They are used to produce or evaluate the value. We can use them to add a character, or number to our data, to combine values, to perform conditional logic with a ternary operator, to run methods on our data, and there are lot of other use cases.

<h1> {{ places }} </h1>

Expression:

{{ places + '?' }}
{{ firstname + ' ' + lastname }}
{{ clicked ? true : false }}
{{ message.split('').reverse().join('') }}

Example :-

Index.html

Instances Index Code

vueinstance.js

Vue Instance js

Output:

Output instances vue

If we want to change Leh & Ladakh to Darjeeling, then the expression would receive the updated value of places. And hence <h1> will be updated accordingly. This is because Vue is reactive. In other words, we can say, the instances data is linked to every place data is being referenced. So if we want to reference places in multiple elements, both elements would update to display the product’s new value. Anywhere that relies on our instance’s data, will update when the data changes.

Index instances
Index JS
Output of instances
  • Now, we will open a console. Here we can change the value of places. For this, we will type in app, which is the name of our Vue instance, then places, which is the name of our data. And give the new value.
Output of Console