Vue.js Instance

Every Vue application starts with a Vue instance. Think of the instance as the brain of your application section. It contains all data, methods, and lifecycle hooks. You can have multiple instances on one page, but most apps use a single root instance.

Anatomy of a Vue Instance - Complete Diagram

+-----------------------------------------------------------+
|                    Vue Instance                           |
|  +-----------------------------------------------------+  |
|  | el: '#app'          (Connects to DOM element)       |  |
|  +-----------------------------------------------------+  |
|  | data: {            (Reactive properties)            |  |
|  |   message: 'Hello',                                 |  |
|  |   count: 0,                                         |  |
|  |   user: { name: 'John' }                            |  |
|  | }                                                   |  |
|  +-----------------------------------------------------+  |
|  | methods: {          (Functions that can use 'this') |  |
|  |   greet() { alert(this.message) }                   |  |
|  | }                                                   |  |
|  +-----------------------------------------------------+  |
|  | computed: {         (Derived values with caching)   |  |
|  |   reversedMsg() { return this.message.split('').   |  |
|  |                       reverse().join('') }          |  |
|  | }                                                   |  |
|  +-----------------------------------------------------+  |
|  | watch: {            (React to data changes)         |  |
|  |   count(newVal) { console.log(newVal) }             |  |
|  | }                                                   |  |
|  +-----------------------------------------------------+  |
|  | lifecycle hooks:    (Run code at specific times)    |  |
|  | created(), mounted(), updated(), destroyed()        |  |
|  +-----------------------------------------------------+  |
+-----------------------------------------------------------+

Creating Your First Vue Instance

// Store instance in a variable (optional but helpful)
const vm = new Vue({
  el: '#app',
  data: {
    product: 'Wireless Mouse',
    price: 29.99,
    quantity: 1
  },
  methods: {
    calculateTotal() {
      return this.price * this.quantity;
    },
    increaseQuantity() {
      this.quantity++;
    }
  }
});

The variable name vm stands for ViewModel. This is a convention from the MVVM (Model-View-ViewModel) pattern. You can name it anything, but vm helps other developers understand your code.

The el Option - Mounting Element

el tells Vue which HTML element to control. Vue will manage everything inside that element. Outside elements remain untouched by this instance. You can use any CSS selector: '#app', '.main-container', or 'div#app'. Vue replaces the content inside the mounted element.

The data Option - Reactive State

data is a JavaScript object. Every property inside becomes reactive. Vue watches each property for changes. When a property changes, Vue re-renders any template that uses that property. You can nest objects and arrays. Vue makes all nested properties reactive too.

Important: Data Must Be an Object in Root Instance

In the root instance, data is an object. In components (covered later), data must be a function that returns an object. This prevents components from sharing data unintentionally.

The methods Option - Functions That Modify Data

methods: {
  updateProduct(newName) {
    this.product = newName;  // 'this' refers to the Vue instance
  },
  applyDiscount(percent) {
    this.price = this.price * (1 - percent/100);
  },
  resetForm() {
    this.product = '';
    this.price = 0;
    this.quantity = 1;
  }
}

Inside methods, the this keyword automatically points to the Vue instance. You can access any data property with this.propertyName. You can call other methods with this.otherMethod().

Accessing Instance Properties and Methods Externally

// After creating the instance
const vm = new Vue({...});

// Access data
console.log(vm.product);      // 'Wireless Mouse'
console.log(vm.$data.product); // same thing

// Change data from outside
vm.product = 'Keyboard';

// Call method
vm.increaseQuantity();

// Check instance properties
console.log(vm.$el);          // The DOM element
console.log(vm.$options);     // Original options object

Properties with $ prefix are Vue's internal properties. Use them for debugging or advanced scenarios. Regular data properties are available directly on the instance.

Multiple Vue Instances on One Page

<div id="header">{{ title }}</div>
<div id="footer">{{ year }}</div>

<script>
  const headerVM = new Vue({
    el: '#header',
    data: { title: 'My Website' }
  });
  
  const footerVM = new Vue({
    el: '#footer',
    data: { year: new Date().getFullYear() }
  });
  
  // Instances are independent
  headerVM.title = 'New Title';  // Only header updates
</script>

Each instance controls its own section. They do not share data unless you explicitly set up communication. For most applications, one instance is enough. Use components for internal separation instead of multiple root instances.

Instance Lifecycle Quick Reference

When you create a Vue instance, it goes through these steps: initialize event system, call beforeCreate, set up reactivity, call created, compile template, call beforeMount, insert to DOM, call mounted, watch for changes, call beforeUpdate and updated when data changes, call beforeDestroy and destroyed when instance is removed.

Leave a Comment