Displaying, Looping, Searching, and Filtering Data Chapter 2
We can now call that method in our view:
<td v-bind:class="activeClass(person)">
{{ activeStatus(person) }}
</td>
I appreciate this is quite a simple execution; let's try a slightly more complex one. We want
to add a conditional class to the balance cell depending on the value. If their balance is
under $2000, we will add an error class. If it is between $2000 and $3000, a warning class
will be applied and if it is over $3000 a success class will be added.
Along with the error, warning and success classes, a class of increasing will be added
if the balance is over $500. For example, a balance of $2,600 will get both the warning, and
increasing classes, whereas $2,400 would only receive the warning class.
As this contains several bits of logic, we will create a use a method in our instance. Create a
balanceClass method and bind it to the class HTML attribute of the cell containing the
balance. To begin with, we'll add the error, warning and success classes.
<td v-bind:class="balanceClass(person)">
{{ formatBalance(person.balance) }}
</td>
In the method, we need to access the balance property of the person passed in and return
the name of the class we wish to add. For now, we'll return a fixed result to verify that it's
working:
balanceClass(person) {
return 'warning';
}
We now need to evaluate our balance. As it's already a number, comparing it against our
criteria won't involve any conversions:
balanceClass(person) {
let balanceLevel = 'success';
if(person.balance < 2000) {
balanceLevel = 'error';
} else if (person.balance < 3000) {
balanceLevel = 'warning';
}
return balanceLevel;
}