Vue.js Instances (original) (raw)

Last Updated : 14 Sep, 2020

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 `

    <!-- 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>

`

Output:

Vue App

Example 2:

HTML `

    <!-- 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>

`

Output: