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
| Property | Purpose |
|---|---|
el | The DOM element Vue controls (CSS selector) |
data | The reactive data that Vue tracks and renders |
methods | Functions available in the template and instance |
computed | Cached properties derived from data |
watch | Watchers 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 eltells Vue which DOM element to controldatacontains reactive properties that update the DOM when changed- Vue proxies data properties onto the instance:
app.nameaccessesdata.name - The
{{ }}syntax outputs data values into the HTML template