Vue.js Instance

Every Vue application starts with a single object called the Vue instance. This instance is the brain of your application. It stores data, defines behavior, and controls what the user sees on the screen.

What Is a Vue Instance?

Think of a Vue instance as the manager of a store. The manager knows all the products (data), decides what to do when a customer makes a request (methods), and watches the store for changes (watchers). The store itself is your webpage.

Diagram: Vue Instance as a Store Manager

┌────────────────────────────────────────┐
│           Vue Instance (Manager)       │
│                                        │
│  data()     → Products in the store    │
│  methods    → Actions the manager takes│
│  computed   → Summaries the manager    │
│               calculates automatically │
│  watch      → Alerts when something    │
│               important changes        │
└──────────────────┬─────────────────────┘
                   │ controls
                   ▼
┌────────────────────────────────────────┐
│         Webpage (The Store)            │
│  <div id="app">...</div>               │
└────────────────────────────────────────┘

Creating a Vue Instance

You create a Vue instance using Vue.createApp() and then attach it to an HTML element using .mount().

<div id="app">
  <p>{{ title }}</p>
</div>

<script>
  const app = Vue.createApp({
    data() {
      return {
        title: "Welcome to Vue.js"
      };
    }
  });

  app.mount("#app");
</script>

Diagram: Instance Creation Flow

Step 1: Vue.createApp({...})
        Creates the Vue instance in memory

Step 2: app.mount("#app")
        Links the instance to the HTML element

Step 3: Vue reads {{ title }} inside #app
        Replaces it with "Welcome to Vue.js"

Step 4: Browser displays:
        "Welcome to Vue.js"

The Options API Structure

Vue uses an object called the options object to configure the instance. Each property inside this object serves a specific purpose.

Vue.createApp({
  data() { ... },       // Stores reactive data
  methods: { ... },     // Contains functions
  computed: { ... },    // Calculates derived values
  watch: { ... },       // Reacts to data changes
  mounted() { ... }     // Runs when app is ready
})

Diagram: The Options Object

┌──────────────────────────────────────────┐
│           Options Object                 │
│                                          │
│  ┌──────────┐  What your app remembers   │
│  │  data()  │  (name, count, items...)   │
│  └──────────┘                            │
│  ┌──────────┐  What your app can do      │
│  │ methods  │  (submit form, add item)   │
│  └──────────┘                            │
│  ┌──────────┐  Values calculated from    │
│  │ computed │  data (total price, etc.)  │
│  └──────────┘                            │
│  ┌──────────┐  Code that runs when       │
│  │  watch   │  specific data changes     │
│  └──────────┘                            │
│  ┌──────────┐  Code that runs at         │
│  │ mounted()│  specific lifecycle times  │
│  └──────────┘                            │
└──────────────────────────────────────────┘

The data() Option

data() is a function that returns an object. Every property in that object becomes reactive — Vue tracks it and updates the page whenever it changes.

data() {
  return {
    userName: "Alex",
    score: 0,
    isLoggedIn: true,
    items: ["Apple", "Banana", "Mango"]
  };
}

You can store text, numbers, booleans, arrays, and objects inside data(). Vue watches all of them automatically.

Why data() Must Be a Function

If you use a plain object instead of a function, all components that use the same data would share the same values — changing one would change all others. A function returns a fresh, separate copy each time, so each component has its own private data.

Diagram: Function Returns Fresh Data Each Time

data() called → returns { count: 0 }  (Component A's own copy)
data() called → returns { count: 0 }  (Component B's own copy)
data() called → returns { count: 0 }  (Component C's own copy)

Component A count changes to 3:
  Component A: count = 3  ✓ Only A is affected
  Component B: count = 0  ✓ Not affected
  Component C: count = 0  ✓ Not affected

The methods Option

Methods are functions you attach to the Vue instance. You call them from your HTML when events happen (like a button click).

<div id="app">
  <p>Count: {{ counter }}</p>
  <button v-on:click="increment">Add One</button>
</div>

<script>
  Vue.createApp({
    data() {
      return { counter: 0 };
    },
    methods: {
      increment() {
        this.counter = this.counter + 1;
      }
    }
  }).mount("#app");
</script>

What this Means Inside Methods

Inside a method, this refers to the Vue instance itself. So this.counter reads the counter property from your data(). Vue automatically makes all data properties accessible through this.

Diagram: Button Click Flow

User clicks "Add One"
        │
        ▼
v-on:click="increment" fires
        │
        ▼
increment() runs
  this.counter = this.counter + 1
  (counter goes from 0 to 1)
        │
        ▼
Vue detects counter changed
        │
        ▼
Vue updates <p>Count: 1</p> on the screen

Accessing the Instance from Outside

When you store the result of Vue.createApp().mount(), you get a reference to the app instance. You can then read or change data from outside the Vue block.

const vm = Vue.createApp({
  data() {
    return { city: "Paris" };
  }
}).mount("#app");

// Later, in the browser console or a script:
console.log(vm.city);   // "Paris"
vm.city = "Tokyo";      // Vue updates the page instantly

Changing vm.city outside the Vue block still triggers Vue's reactivity — the page updates automatically.

The Mounted Lifecycle Hook

Vue instances go through stages: creation, mounting, updating, and unmounting. You can run code at each stage using lifecycle hooks.

The mounted() hook runs once, right after Vue inserts your app into the webpage. It is a good place to fetch data from a server when the page first loads.

Vue.createApp({
  data() {
    return { users: [] };
  },
  mounted() {
    // This runs once when the app appears on screen
    console.log("App is ready!");
    // Good place to load data from a server
  }
}).mount("#app");

Diagram: Key Lifecycle Stages

Vue.createApp() is called
        │
        ▼
  beforeCreate() ← runs before data is set up
        │
        ▼
   created()     ← data is ready, page not yet updated
        │
        ▼
  beforeMount()  ← Vue is about to write to the browser
        │
        ▼
   mounted()     ← App is visible, safe to load server data
        │
        ▼
  [Data changes → updated() runs]
        │
        ▼
  [App removed → unmounted() runs]

Multiple Vue Apps on One Page

You can run more than one Vue instance on the same page. Each instance controls only its own container element and has its own independent data.

<div id="clock">{{ time }}</div>
<div id="weather">{{ temp }}</div>

<script>
  Vue.createApp({ data() { return { time: "10:30 AM" }; } }).mount("#clock");
  Vue.createApp({ data() { return { temp: "22°C" }; } }).mount("#weather");
</script>

Diagram: Two Independent Vue Instances

Page
├── #clock  ← Controlled by Vue App 1 (knows about time)
└── #weather ← Controlled by Vue App 2 (knows about temp)

App 1 data change → only #clock updates
App 2 data change → only #weather updates

Summary

The Vue instance is the foundation of every Vue application. You create it with Vue.createApp() and connect it to HTML with .mount(). Inside the instance, data() holds your reactive values, methods holds your functions, and lifecycle hooks like mounted() let you run code at the right time. Every Vue component you build in larger applications is built on these same principles.

Leave a Comment

Your email address will not be published. Required fields are marked *