Understanding the Vue Instance
What is a Vue Instance? Well, it’s a single occurrence of a Vue.js object. The Vue instance is the most important thing to understand because it literally controls the section of the web page or application that you instruct it too. Once you understand the instance, the better you’ll understand more complex things, like how Vue CLI scaffolds a new project and how single file .vue
components work.
This section of the chapter will refer in bold to the file names of where the code lives. This is done so you can better understand how Vue.js talks to the different pages and files. The file structure for this hypothetical application is something like this:
project-folder/
|__index.html
|__app.js
The Vue.js library and the app.js
file (Vue Instance) are referenced in the index.html
file via a <script>
tag.
app.js
var
vm
=
new
Vue
({
// options
});
This instance doesn’t do much. In fact, it doesn’t do anything at all. If you were to add this to a webpage, you wouldn’t see anything. However, Vue.js is already initialized and ready to be used.
Note: If you are using ES6, it’s always recommended to use const
or let
.
The Vue instance accepts options or properties that you can add to enhance the functionality of your application. These are things like, el
, data
, methods
, computed
, and much more.
app.js
var
vm
=
new
Vue
({
el
:
'#app'
,
data
:
{
name
:
'Dave Berning'
,
hometown
:
'Cincinnati, OH'
,
},
});
Let’s dissect this instance. The most important property is el
because it defines which part of our application this Vue Instance should control. Without it, Vue.js cannot function; it’s required. In this case, Vue.js will “control” all of the HTML that’s inside of the <div id="app"><div>
element.
You could have an HTML file that has multiple <div>
’s:
index.html
<div
id=
"app"
>
<p>
My name is, {{ name }}<p>
</div>
<div
id=
"contact-form"
>
<form>
...
</form>
</div>
Since the el
property in the Vue instance has a value of #app
, Vue.js will only modify the HTML in the first div; it will never touch the contact form. Unless you create another Vue instance and make the el
in the second instance have a value of #contact-form
. However, it’s always recommended to have just one Vue Instance at a time.
The Data Property
The data
property stores all of your data that you want to display or modify in the HTML of the Vue instance. Any information that you declare in the data
property instantly becomes reactive. Reactive meaning that your data can change based on user interactions. Reactive properties are also bound in two-ways; when the data property is updated, any instance of that property is also updated. To display your data into your HTML view, use interpolation by using the mustache ({{ }}
) syntax. If you’ve used AngularJS in the past, this should be familiar to you.
index.html
<div
id=
"app"
>
<p>
Hi, my name is {{ name }}. I am from {{ hometown }}.</p>
</div>
app.js
var
vm
=
new
Vue
({
el
:
'#app'
,
data
:
{
name
:
'Dave Berning'
,
hometown
:
'Cincinnati, OH'
,
},
});
Your view should read: Hi, my name is Dave Berning. I am from Cincinnati, OH. Try modifying your data by either changing the data properties or by adding additional properties, and use interpolation to display it out into your HTML view.
The Methods Property
The method
property does what you would expect it to: it stores methods or functions that you can use across your application. These functions can either be used to execute something on one of Vue’s lifecycle methods (more on that later), running business logic or by returning a value that you can later use in your HTML view.
Let’s build off of the Vue Instance above.
Note: All of the examples in this book will be using the ES6 syntax, which requires a compiler like Babel to run in the browser. You are more than welcome to use TypeScript or the more supported ES5 syntax, which doesn’t require a compiler.
app.js
var
vm
=
new
Vue
({
el
:
'#app'
,
data
:
{
name
:
'Dave Berning'
,
hometown
:
'Cincinnati, OH'
,
},
methods
:
{
showDataOnMounted
()
{
console
.
log
(
this
.
name
);
console
.
log
(
this
.
hometown
);
},
},
mounted
()
{
this
.
showDataOnMounted
();
},
});
In this example, there is an instance method that console logs the name
and hometown
data properties when the Vue Instance is mounted. You might also notice that we are using this
a lot in the instance. That’s because this
in Vue, refers to the Vue Instance, not the function. If you want to access the name
data property, you can access it with this.name
. To use name
in your HTML via interpolation, just omit the this
and use name
. The same refers to any method or object.
Let’s write a method that returns something to your HTML view.
index.html
<div
id=
"app"
>
<p>
Hi, my name is {{ name }}. I am from {{ hometown }}</p>
<p>
{{ numberOfSomething(someNumber, 'dogs') }}</p>
</div>
app.js
var
vm
=
new
Vue
({
el
:
'#app'
,
data
:
{
name
:
'Dave Berning'
,
hometown
:
'Cincinnati, OH'
,
someNumber
:
2
,
},
methods
:
{
numberOfSomething
(
number
,
something
)
{
return
`I have
${
number
}
${
something
}
.`
;
},
},
});
The numberOfSomething
function accepts two arguments: a number and something. As demonstrated above, methods do not need to be called exclusively in the Vue Instance in the <script>
tag; it can also be referenced in the HTML view and accept arguments. When wrapped in curly braces, the method is ran and the method returns the string, “I have 2 dogs.”.
The Computed Methods Property
One common mistake with new Vue developers (including myself, I must admit) is mixing up computed properties with methods that return a value. When used correctly, computed methods are great for a couple of reasons: 1) the value returned gets stored as if it was a data
property (becomes reactive), and 2) computed properties are cached and stored.
Much like a method
, computed properties can also perform logic and return something. The main difference between computed properties and methods are, computed properties cannot accept arguments. Computed properties are essentially used to perform logic, and return and store a value.
A method that should be a computed property (bad)
index.html
<div
id=
"app"
>
<p>
You have {{ dogCount }} {{ dogs() }}</p>
</div>
app.js
var
vm
=
new
Vue
({
el
:
'#app'
,
data
:
{
dogCount
:
2
,
},
methods
:
{
dogs
()
{
if
(
this
.
dogCount
===
1
)
{
return
'dog'
;
}
else
{
return
'dogs'
;
}
},
},
});
Your view should read: You have 2 dogs. If you change your dogCount
to 1, it should read: You have 1 dog.
Computed properties, the proper way (good)
index.html
<div
id=
"app"
>
<p>
You have {{ dogCount }} {{ dogs }}</p>
</div>
app.js
var
vm
=
new
Vue
({
el
:
'#app'
,
data
:
{
dogCount
:
2
,
},
computed
:
{
dogs
()
{
if
(
this
.
dogCount
===
1
)
{
return
'dog'
;
}
else
{
return
'dogs'
;
}
},
},
});
Your view should still display the same information in the view. However, in this example, computed properties are being used appropriately.
A good rule of thumb when deciding to use computed properties or methods is: If you need to pass in an argument to return a certain value, always use methods. If you need to perform logic and return a value without any arguments, always use computed properties.
The Watch Property
The watch property is very similar to the computed property. They both react to a change in data, both can react to change in other data property, and both can be used as a data
property. The main difference between the two properties is that the watch
property is more generic than a computed property. Watch properties are more likely to be used if you have expensive operations in response to changing data or if you want to perform asynchronous tasks.
The watch property name must match that of the data property it’s watching.
var
vm
=
new
Vue
({
el
:
'#app'
,
data
:
{
favoriteFramework
:
'Vue.js'
,
},
watch
:
{
favoriteFramework
()
{
...
}
},
});
Lifecycle Methods
Lifecycle methods or “lifecycle hooks” are a way to perform functions or tasks during an instance’s lifecycle (i.e. run something when the component is created
, mounted
, destroyed
, etc.).
Below is a list of all the current lifecycle hooks in Vue.js 2 at the time of writing. The most commonly used hooks are: created
, beforeMount
, mounted
, and destroyed
.
beforeCreate
created
beforeMount
mounted
beforeUpdate
activated
deactivated
beforeDestroy
destroyed
errorCaptured
Below is an easily digestible graph that is on the Vue.js documentation website.
You use lifecycle methods like any other instance property.
app.js
var
vm
=
new
Vue
({
el
:
'#app'
,
data
:
{
...
},
beforeMount
()
{
console
.
log
(
'I am executed before the component or instance is mounted!'
);
},
mounted
()
{
console
.
log
(
'I am executed when the component or instance is mounted!'
);
},
destroyed
()
{
alert
(
'I am defeated!'
);
}
});