Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Optimizing your App and Using Components to Display Data Chapter 3

With components, a new instance is created every time it is called, so we can rely on the


person object we passed in via a prop and no longer need to pass the person into the


function. Remove the parameter from the function and the view—also update any reference


to person inside the function to this.person to reference the object stored on the


component:


computed: {
/**
* CSS Classes
*/
activeClass() {
return this.person.isActive? 'active' :
'inactive';
},
balanceClass() {
let balanceLevel = 'success';
if(this.person.balance < 2000) {
balanceLevel = 'error';
} else if (this.person.balance < 3000) {
balanceLevel = 'warning';
}
let increasing = false,
balance = this.person.balance / 1000;
if(Math.round(balance) == Math.ceil(balance)) {
increasing = 'increasing';
}

return [balanceLevel, increasing];
}
},

The part of our component template that utilizes this function should now look like:


<td v-bind:class="balanceClass">
{{ format(person, 'balance') }}
</td>

Formatted value functions

When it comes to moving the format() function to the component for formatting our data,


we are faced with two options. We can move it like-for-like and put it in the methods


object, or we can take advantage of the Vue caching and conventions and create a
computed function for each value.

Free download pdf