vuejs
  1. vuejs-class-and-style-bindings

Vue.js Class and Style Bindings

Vue.js provides convenient ways to bind class names and inline styles to HTML elements using the v-bind directive. The class and style bindings can also be combined with other directives to create complex dynamic templates.

Syntax

Class Binding Syntax

<div v-bind:class="{ classObject }"></div>
<div v-bind:class="[ classArray ]"></div>
<div v-bind:class="[ classObject, classArray ]"></div>

Style Binding Syntax

<div v-bind:style="{ styleObject }"></div>
<div v-bind:style="[ styleObject, styleArray ]"></div>

Example

Class Binding Example

<template>
  <div v-bind:class="{ active: isActive }">Class Binding Example</div>
</template>
<script>
export default {
  data() {
    return {
      isActive: true
    }
  }
}
</script>

Style Binding Example

<template>
  <div v-bind:style="{ color: fontColor, 'font-size': fontSize + 'px' }">Style Binding Example</div>
</template>
<script>
export default {
  data() {
    return {
      fontColor: 'red',
      fontSize: 20
    }
  }
}
</script>

Output

Class Binding Output

<div class="active">Class Binding Example</div>

Style Binding Output

<div style="color: red; font-size: 20px;">Style Binding Example</div>

Explanation

Class Binding Explanation

The v-bind:class directive allows you to bind a class to an element conditionally, based on the data state. The class binding can be either a CSS class object or an array of CSS classes.

Style Binding Explanation

The v-bind:style directive allows you to bind styles to an element conditionally based on the data state. The style binding can be a CSS style object or an array of CSS style objects.

Use

The class and style bindings are useful to conditionally apply classes and styles based on data state. They can be used with other Vue.js directives to create dynamic templates, such as toggling the visibility of an element or animating elements.

Important Points

  • The syntax for class and style bindings is similar, but they serve different purposes.
  • Class bindings can be used to toggle CSS classes conditionally, whereas style bindings can be used to toggle CSS styles conditionally.
  • Both class and style bindings can be combined with other Vue.js directives to create more dynamic templates.

Summary

The class and style bindings are powerful tools for conditionally applying classes and styles to HTML elements based on data state. Both bindings can be used with other Vue.js directives to create dynamic templates, making it easier to manage complex components and interfaces. Understanding the syntax and use cases of these directives is essential for building high-performance Vue.js applications.

Published on: