Vue Class and Style Bindings

Tram Ho

A common need for data binding is to manipulate an element’s classlist and its inline types. Since both are properties we can use v-bind to handle them: we just need to compute a final string with our expressions. However, interfering with string concatenation is very annoying and error prone. For this reason, Vue provides special enhancements when v-bind is used with classes and styles. In addition to strings, expressions can also evaluate to objects or arrays.

Binding HTML Classes

During development you want to add a class to an HTML tag with a certain condition occurring. Then Vue can help you do this very easily.

Object syntax

You can pass an object to v-bind:class to dynamically use classes:

get it

In the above example we can see class active added, because we use v-bind:class declare variable isActive default value is true provided the default is true { active: isActive } or we can also use { active: isActive == true } . In the HTML part, we have the above text that will be displayed in red because of the active class.

When you need to bind many classes, please do the following:

Data:

get it

We can pass an object to the :class like this:

Result

Classes are bound when true

Array syntax

We can pass an array to v-bind:class to apply a list of classes:

data

Results

  • You can conditionally convert a class in a list, you can do it with a ternary expression:

  • You can also use

data

Results

Binding Inline Styles

Object syntax

html

Js

We use with 1 object to be more neat

JS

The results are the same

Array syntax

You can use the array method for v-bind:style which allows you to apply multiple style objects to the same element: html

Js

This article is quite simple so you can bind HTML tags when rendering depending on certain conditions. Hope you can understand and then bind yourself in different ways for different purposes.

Share the news now