How to Bind Class & Style in Vue.js
In this article, we’re going to learn how to toggle class names in Vue.js. Let’s see:
Table of Contents
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>
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.