Introduction

Vue.js provides a powerful way to dynamically apply CSS classes to elements based on data and conditions. This feature is particularly useful for creating interactive and responsive user interfaces. In this guide, we'll explore how to bind CSS classes dynamically in Vue.js and provide sample code to demonstrate the process.


Sample Code

Let's create a Vue.js application that showcases dynamic styling by binding CSS classes:


<div id="app">
<div :class="{'active': isActive, 'error': hasError}">
This is a dynamic CSS class example.
</div>
<button @click="toggleClasses">Toggle Classes</button>
const app = new Vue({
el: '#app',
data: {
isActive: false,
hasError: false
},
methods: {
toggleClasses() {
this.isActive = !this.isActive;
this.hasError = !this.hasError;
}
}
});

In this code:

  • We create a Vue component with a `div` element that uses the `:class` binding to conditionally apply CSS classes based on the values of the `isActive` and `hasError` data properties.
  • The `isActive` and `hasError` data properties are initially set to `false`, which determines the initial state of the CSS classes applied to the `div` element.
  • We also include a button that, when clicked, triggers the `toggleClasses` method to toggle the values of `isActive` and `hasError`, dynamically changing the CSS classes on the `div` element.