Introduction
Class and style bindings fulfil the need to dynamically add styles based on certain conditions. Add multiple classes, styles when need be. Vue.js is done with “v-bind”, a directive that manipulates the DOM when applied to the HTML.
How to use class binding?
<template>
<div>
<h1 class="temp">class binding</h1>
</div>
</template>
<script>
export default {
name: "Home",
};
</script>
<style scoped>
.temp {
color: red;
}
</style>
Here we have added class temp just as it is added in a simple HTML file.
Can we add classes conditionally?
Yes!
Refer to below examples--
Using the object syntax
<template>
<div>
<h1 :class="{temp: true}"></h1>
</div>
</template>
<script>
export default {
name: "Home",
};
</script>>
<style scoped>
.temp {
color: red;
}
</style>The above conditional styling is done to an HTML element, and the rendered element will be:
<h1 class=”temp”></h1>
The temp class will be added to the class list of h1 if temp is true.
Using the array syntax
v-bind:class need to be applied for adding a list of classes to the element
<template>
<div>
<h1 v-bind:class="[active, error]">array syntax</h1>
<div>
</template>
<script>
export default {
name: "Home",
data() {
return {
active: true,
error: false,
};
},
};
</script>
<style>
.active {
}
.text-danger {
color: red;
}
</style>
We have declared strings of classes in the data object and used them inside a list of classes, which will render
<h1 class=”active error”> array syntax</h1>
We can use strings inside of list, without declaration stuff
<h1 v-bind:class=”[“active”,text-danger”]”>array syntax</h1>
If we want to conditionally add class:
<h1 v-bind:class=”[isActive?active:””,hasError?error:””]>
And if :
data{
isActive:true,
hasError:false,
Active:”active”,
error:”text-danger”
}
The rendered element would be:
<h1 class=”active”>array syntax</h1>
Also for multiple conditional classes, we can use object syntax inside of array syntax as below:
<h1 v-bind:class=”[{active:isActive},error]”>array syntax </h1>
Use with components
Let’s first see how we add class to components. We declare a component as follows with an h1 element
Vue.component('my-component', {
template: '<h1 class="fun dang">Hello :)</h1>'
})
Now we add classes to comp when using it
<my-component class=”hello”></my-component>
The rendered html would be
<h1 class=”fun dang hello”>Hello :)</h1>
We can add class based on condition just as we added in html elements
<my-component v-bind:class=”{active:isActive}”></my-component>
If isActive is true, the active class will be added and vice versa




