Properties and Methods


Properties

Each Vue instance has a few reserved properties. We've already discussed the "data" and "el"properties.

In this chapter, we review methods and computed properties. 


Methods

Vue methods are exactly like JavaScript functions and the syntax is the same. You just have to remember to define them inside the "methods" property: 

new Vue({
el: '#app',
data: {
counter: 0
},
methods: {
increaseCounter() {
this.counter ++;
},
decreaseCounter() {
this.counter --;
}
}
})

Notice that I'm using the ES6 syntax for defining the methods. If you're not already familiar with it, you should. It is very simple yet efficient. 

We'll learn about how to call methods in events chapter


Computed properties

We learned about data and how to display them into the DOM with Vue. Yet in many cases, we need a modified version of the data before displaying it. That's what exactly computed properties are for. 

In other words, computed properties are functions that return a computed value. 

Computed properties are reactive. Meaning their value changes by changing their relative data. They are very useful in scenarios where the value of one variable depends on one or more other variables.

Let's define a computed property:

new Vue({
el: '#app',
data: {
firstName: 'John',
lastName: 'Doe'
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName;
}
}
});

And call it:

<h1>{{ fullName }}</h1>

Creating filters with computed properties

If you're coming from the world of AngularJS or Vue 1.0, you might have heard of the concept of filters. 

Using computed properties we can easily create our very own filters. 

Let's say we have a tasks list and we need to display only the completed tasks:

new Vue({
el: '#app',
data: {
tasks: [
{ id: 1, title: 'get up from bed', completed: true },
{ id: 2, title: 'turn on the computer', completed: true },
{ id: 3, title: 'open iTunes', completed: false },
{ id: 4, title: 'Listen to some Pink Floyd', completed: false },
{ id: 5, title: 'Go to bed', completed: false }
]
},
computed: {
unfinishedTasks() {
return this.tasks.filter((item) => {
return item.completed === false;
});
}
}
});
<h1>All Tasks:</h1>
<ul>
<li v-for="item in tasks">{{ item.title }}</li>
</ul>
<h1>Unfinished Tasks:</h1>
<ul>
<li v-for="item in unfinishedTasks">{{ item.title }}</li>
</ul>

Of course you have access to computed properties inside the Vue instance as well. Let's say I need to get all the completed tasks inside a method, I can reach it withthis.unfinishedTask

Since computed properties are reactive, by changing "tasks" array the items of "unfinishedTasks" will change as well. 


Comments: