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

Binding a CSS class is similar to other attributes. The value takes an object that can calculate


logic from within the view or be abstracted out into our Vue instance. This all depends on
the complexity of the operation.


First, let's add a class to the cell containing the isActive variable if the user is active:


<td v-bind:class="{ active: person.isActive }">
{{ activeStatus(person) }}
</td>

The class HTML attribute is first prepended by v-bind: to let Vue know it needs to


process the attribute. The value is then an object, with the CSS class as the key and the


condition as the value. This code toggles the active class on the table cell if the


person.isActive variable equates to true. If we wanted to add an inactive class if the


user was not active, we could add it to the object:


<td v-bind:class="{ active: person.isActive, inactive:
!person.isActive }">
{{ activeStatus(person) }}
</td>

Here's we've used the exclamation point again to reverse the status. If you run this app, you
should find the CSS classes applied as expected.


If we're just applying two classes based on one condition, a ternary if statement can be


used inside of the class attribute:


<td v-bind:class="person.isActive? 'active' : 'inactive'">
{{ activeStatus(person) }}
</td>

Note the single quotes around the class names. Once again, however, logic has started to


creep into our View and, should we wish to also use this class elsewhere, is not very


scalable.


Create a new method on our Vue instance called activeClass and abstract the logic into


that — not forgetting to pass the person object in:


activeClass(person) {
return person.isActive? 'active' : 'inactive';
}
Free download pdf