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

(singke) #1
Displaying, Looping, Searching, and Filtering Data Chapter 2

In the preceding method, the class output gets set to success by default, as we only need


to change the output if it is less than 3000. The first if checks whether the balance is below


our first threshold – if it does, it sets the output to error. If not, it tries the second


condition, which is to check whether the balance is below 3000. If successful, the class


applied becomes warning. Lastly, it outputs the chosen class, which applies directly to the


element.


We now need to consider how we can do the increasing class. To get it to output


alongside the existing balanceLevel class, we need to convert the output from a single


variable to an array. To verify that this works, hardcode the extra class to the output:


balanceClass(person) {
let balanceLevel = 'success';
if(person.balance < 2000) {
balanceLevel = 'error';
} else if (person.balance < 3000) {
balanceLevel = 'warning';
}
return [balanceLevel, 'increasing'];
}

This adds the two classes to the element. Convert the string to a variable and set to false


by default. Vue won't output anything for a false value passed in the array.


To work out if we need the increasing class, we need to do some calculations on the


balance. As we want the increasing class if the balance is above 500 no matter what range it
is in, we need to round the number and compare:


let increasing = false,
balance = person.balance / 1000;

if(Math.round(balance) == Math.ceil(balance)) {
increasing = 'increasing';
}

Initially, we set the increasing variable to false as a default. We also store a version of


the balance divided by 1000. The means our balances turn out to be 2.45643 instead of


2456.42. From there, we compare the number after it has been rounded by JavaScript (For


example 2.5 becomes 3, whereas 2.4 becomes 2) to the number that has been forced to


round up (example 2.1 becomes 3, along with 2.9).

Free download pdf