vue

Class Binding in Vue with Vue v-bind


In this guide, we will look at class binding with the Vue v-bind directive.
Class binding comes in handy when we have the need of manipulating an element’s class list.

We can either pass an object or array to dynamically toggle a class.

Object Syntax

<template>
<div v-bind:class="{ active: isActive == 1 }"></div>
</template>

<script>
export default {
  data() {
    return {
      isActive: 1
    };
  }
};
</script>

<style scoped>
.active{
    background: tomato;
    height: 50px;
    width: 50px;
}
</style>


The above syntax means that the class active would be present on the said element( a div in this instance ) as long as the expression evaluates to true.

Multiple classes can also be bound as seen here:

  <div
    class="static"
    v-bind:class="{ active: isActive, error: hasError }"
  ></div>

Array Syntax
We can as well pass an array to apply a list of classes.

<div v-bind:class="[active, error]"></div>


Share on social media

//