Vue.js greatly reduces the amount of work you’d otherwise need to do to achieve something in vanilla JavaScript. Since Vue.js is a progressive UI framework, it makes any UI mutation really easy with it’s powerful reactivity features. You can easily bind and unbind a CSS class using Vue.js as follows:
<template>
<div id="app">
<button @click="isDanger = !isDanger">Toggle danger</button>
<div
:class="{ danger: isDanger, safe: !isDanger }"
style="margin-top: 15px"
>
{{ isDanger ? "Danger" : "Safe" }}
</div>
</div>
</template>
<script>
export default {
name: "App",
data() {
return { isDanger: false };
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
padding: 24px;
font-size: 20px;
}
button {
background-color: #004cbe;
color: #ffffff;
border: 0px;
border-radius: 6px;
padding: 6px 20px;
margin-right: 1em;
cursor: pointer;
transition: all 0.3s;
}
button:hover {
background-color: #2f79e7;
transition: all 0.3s;
}
.danger {
color: red;
}
.safe {
color: green;
}
</style>
Code language: HTML, XML (xml)
In the above code, I have a reactive state called isDanger on line 17. This state will toggle it’s value whenever someone clicks on the Toggle danger button placed on line 3.
I’ve then conditionally bind two CSS classes named danger and safe on line number 5. One of these two CSS classes will be active once at a time based on the truthiness of isDanger state.
Binding multiple classes
Of course, you can also bind multiple classes to an element. Some of these can be conditional based, while others may remain bind without any conditions. For instance, I want to bind a CSS class called ‘large-texts’ at all times. The modified parts of the code would then look like:
<div
:class="[
isDanger ? 'danger' : '',
!isDanger ? 'safe' : '',
'large-text'
]"
style="margin-top: 15px"
>
{{ isDanger ? "Danger" : "Safe" }}
</div>
// css
.large-text {
font-size: 30px;
}
Code language: HTML, XML (xml)
You can find a working demo of the above code from my repos here: