Getting Started with Vue.js

Applying Classes with Vue

Best Practices with JavaScript and Styles

When applying styles to our HTML using JavaScript, it is best practice to not apply styles directly. We don't want to do something like:

document.querySelector('h2').style.background = 'red';

CSS should be responsible for applying styles, JavaScript shouldn't be worried about how to style our elements.

A best practice is to use JavaScript to apply CSS classes and let the CSS handle styling.

By doing this, we ensure a separation of duties between JavaScript and CSS:

  • JavaScript is responsible for adding and removing classes
  • CSS is responsible for styling those classes

This way, we'll never have to go digging into our JavaScript code to see if there's a specific style applied.

Applying Classes in Vue

To apply classes using Vue, we can use the v-bind directive to bind directly to the class attribute.

In order to bind to the classes, we will pass in an object. The keys will be the class to be applied and the value will be the variable that Vue should evaluate for truthiness.

<button v-bind:class="{ 'class-to-apply': shouldApplyClass }">My Button</button>

In this scenario, class-to-apply would only be added if shouldApplyClass evaluates to true.

Ways to Apply Classes

There are three main ways to apply classes in Vue:

  • inline object
  • data object
  • array

Inline Objects

Passing in an object directly to the v-bind:class is the simples way we can apply classes using Vue.

<div class="notification" v-bind:class="{ 'is-success': isSuccessful, 'is-size-1': isLarge }">
    I am a notification!
</div>

Data Object

Inline objects can complicate our templates if they become large. We can move all that information into our Vue instance so that our templates are much cleaner.

<div id="app">
<div class="notification" v-bind:class="{ 'is-success': isSuccessful, 'is-size-1': isLarge }">
    I am a notification!
</div>
</div>
const app = new Vue({
    el: '#app',
    data: {
        notificationStyles: { 
            'is-success': true, 
            'is-size-1': true 
        }
    }
});

Array

An array is a little different than passing in the object of classes. An array will look at the variables passed in and just use those classes directly.

For instance, we can have some variables like so:

const app = new Vue({
    el: '#app',
    data: {
        classOne: 'is-danger',
        classTwo: 'is-large'
    }
});

We can then apply those classes using an array:

<div id="app">
<div class="notification" v-bind:class="[classOne, classTwo]">
    I am a notification!
</div>
</div>