Episode 2 of 44

The Vue Instance

Understand the Vue instance — the core of every Vue application — and how it connects your data to the DOM.

The Vue Instance

Every Vue application starts with a Vue instance. It is the root of your app — the bridge between your data and the DOM. In this episode you will learn how to create a Vue instance and understand its key properties.

Creating a Vue Instance

var app = new Vue({
    el: '#app',
    data: {
        name: 'Shaun',
        job: 'Ninja'
    }
});

The Options Object

PropertyPurpose
elThe DOM element Vue controls (CSS selector)
dataThe reactive data that Vue tracks and renders
methodsFunctions available in the template and instance
computedCached properties derived from data
watchWatchers that react to data changes

The el Property

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

<div id="other">
    <p>{{ name }}</p>  <!-- This will NOT work -->
</div>

The el property tells Vue which DOM element to control. Vue only manages the element specified by el and everything inside it. Content outside that element is not reactive.

Reactive Data

var app = new Vue({
    el: '#app',
    data: {
        name: 'Shaun',
        job: 'Ninja'
    }
});

// You can change data from outside:
app.name = 'Ken';  // The DOM updates automatically!
app.job = 'Samurai'; // The DOM updates automatically!

Vue makes the data object reactive. When you change a property, Vue detects the change and re-renders the parts of the DOM that use that property. This happens automatically — you never need to manually update the HTML.

Accessing Data via the Instance

var app = new Vue({
    el: '#app',
    data: {
        name: 'Shaun'
    }
});

console.log(app.name);     // 'Shaun' — proxied from data
console.log(app.$data.name); // 'Shaun' — direct access to data object
console.log(app.$el);       // The DOM element

Vue proxies all data properties onto the instance itself, so app.name is a shortcut for app.$data.name. Properties prefixed with $ are Vue's built-in instance properties.

Using the Template

<div id="app">
    <h1>{{ name }}</h1>
    <p>Job: {{ job }}</p>
    <p>{{ name }} is a {{ job }}</p>
</div>

Inside the element controlled by Vue, you can use {{ }} to output any data property. You can also use JavaScript expressions inside the curly braces: {{ name.toUpperCase() }} or {{ age + 5 }}.

Key Takeaways

  • Every Vue app starts with new Vue({ }) — the Vue instance
  • el tells Vue which DOM element to control
  • data contains reactive properties that update the DOM when changed
  • Vue proxies data properties onto the instance: app.name accesses data.name
  • The {{ }} syntax outputs data values into the HTML template