A Vue.js application starts with a Vue instance. The instances object is the main object for our Vue App. It helps us to use Vue components in our application. A Vue instance uses the MVVM(Model-View-View-Model) pattern. The Vue constructor accepts a single JavaScript object called an options object. When you instantiate a Vue instance, you need to pass an options object which can contain options for data, methods, elements, templates, etc.
Syntax:
var app = new Vue({ // options });
Approach: First, we need to create an object to use Vue and assigning it to the variable app. In Vue, there is a parameter called el which takes the id of the DOM element. So we will create a div element with id as home. Vue elements will work within this id(#home) only. We can assign values of parameters inside this data object.
In the following examples, we use Vue.js to show the working of instances.
Example 1:
HTML
<!DOCTYPE html> < html > < head > </ script > </ head > < body > < div style = "text-align: center;" id = "home" > <!-- Rendering data to DOM --> < h1 style = "color: seagreen;" >{{title}}</ h1 > < h2 >Title : {{name}}</ h2 > < h2 >Topic : {{topic}}</ h2 > </ div > < script type = "text/javascript" > // Creating Vue Instance var app = new Vue({ // Assigning id of DOM in parameter el: '#home', // Assigning values of parameters data: { title: "Geeks for Geeks", name: "Vue.js", topic: "Instances" } }); </ script > </ body > </ html > |
Output:
Example 2:
HTML
<!DOCTYPE html> < html > < head > </ script > </ head > < body > < div style = "text-align: center;" id = "home" > <!-- Rendering data to DOM --> < h1 style = "color: seagreen;" > {{title}} </ h1 > < h1 >Enter first name : < input type = "text" id = "firstname" > </ h1 > < h1 >Enter last name : < input type = "text" id = "lastname" > </ h1 > < button @ click = "fullname()" >Click</ button > < h2 id = "full_name" ></ h2 > </ div > </ body > < script type = "text/javascript" > // Creating Vue Instance var app = new Vue({ // Setting id of DOM in parameter el: '#home', // Passing datas data: { title: "Geeks for neveropen", }, methods: { fullname: function () { // Getting values from inputs var first_name = document .getElementById("firstname").value var last_name = document .getElementById("lastname").value // Setting text in element document.getElementById("full_name") .innerHTML = "Hi, " + first_name + " " + last_name } } }); </ script > </ html > |
Output: