Open In App

How to create instance in Vue.js ?

A Vue.js Instance refers to a Vue constructor’s instance in the Vue application. It acts as a container that holds your application’s data and methods. Vue.js implements the Component-Based Architecture that enables the generation of these instances, in order to represent and manage individual components or specific sections of the Vue Application. Each Instance is responsible for performing the specific task that enhances the functionality & interface of the web application. In this article, we will learn how to create a VueJS instance.

Syntax

In the below code snippet, new Vue({…}) initializes a new Vue instance and accepts an object with various options and data properties.



const app = new Vue({
    setup() {
        // Your code here
    }
})

Vue.JS installation

There are the following ways to install Vue.JS:

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

Write the following command in the terminal



npm install vue

Approach

To create an instance in VueJS, follow the below steps:

Example 1: In this example, we will be creating a simple VueJS Instance that renders the Hello GeeksforGeeks text.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <script src=
    </script>
</head>
  
<body>
    <div id="app">{{ message }}</div>
  
    <script>
        const { createApp, ref } = Vue
  
        createApp({
            setup() {
                const message = ref('Hello GeeksforGeeks')
                return {
                    message
                }
            }
        }).mount('#app')
    </script>
</body>
  
</html>

Output:

Example 2: In this example, we will create a simple VueJS instance representing a counter app.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <script src=
    </script>
</head>
  
<body>
    <div id="app">
        <button @click="incrementCount">
            Click Me!
        </button>
        <p>
            Button Clicked {{ count }}
            times
        </p>
    </div>
  
    <script>
        const { createApp, ref } = Vue
        createApp({
            setup() {
                const count = ref(0)
          
                const incrementCount = () => {
                    count.value++
                }
          
                return {
                    count,
                    incrementCount
                }
            }
        }).mount('#app')
    </script>
</body>
  
</html>

Output:


Article Tags :