How to Bind Class & Style in Vue.js

Published on January 24, 2020 1 min read

In this article, we’re going to learn how to toggle class names in Vue.js. Let’s see:

Table of Contents

  1. Object Binding (Class)
  2. Array Binding (Class)
  3. Inline CSS Binding

Object Binding (Class)

The syntax of object binding is:

<div :class="{className:propertyName}">

If the propertyName is true, then className will be shown. Let’s see an example:

<template>
    <div>
        <h3 :class="{active:isActive}">Hello MyNotePaper</h3>
        <button @click="isActive=!isActive">Click me</button>
    </div>
</template>

<script>
    export default {
        data: function () {
            return {
                isActive: false
            }
        }
    }
</script>

<style>
    .active {
        color: green;
    }
</style>

In the example, if we click the button, isActive property will true and active class will be shown. And if we click the button again, the isActive property will false and the active class will be hidden.

Array Binding (Class)

The syntax of array binding:

<div :class="[propertyName?'classNameA':'classNameB']">

This syntax means if propertyName is true, classNameA will be shown and if false, classNameB will be shown.

Here’s an example of array binding:

<template>
    <div>
        <h3 :class="[isActive?'green':'red']">Hello MyNotePaper</h3>
        <button @click="isActive=!isActive">Try me</button>
    </div>
</template>

<script>
    export default {
        data: function () {
            return {
                isActive: false
            }
        }
    }
</script>

<style>
    .green {
        color: green;
    }
    .red {
        color: red;
    }
</style>

Inline CSS Binding

The syntax of inline CSS binding:

<div :style="{'css-propertyName':properyName}">

Let’s see an example:

<template>
    <div :style="{ 'color': color }">
        <h3>Hello MyNotepaper</h3>
        <button @click="color = 'red'">Red color</button>
        <button @click="color = 'green'">Green color</button>
    </div>
</template>

<script>
    export default {
        data: function() {
            return {
                color: ""
            };
        }
    };
</script>

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write article on Laravel, Linux server, modern JavaScript and more on web development.

Follow