A common need for data binding is manipulating an element’s class list and its inline styles. Since they are both attributes, we can use v-bind to handle them: we only need to calculate a final string with our expressions. However, meddling with string concatenation is annoying and error-prone. For this reason, Vue provides special enhancements when v-bind is used with class and style. In addition to strings, the expressions can also evaluate to objects or arrays

A common requirement for data bindings is to manipulate an element’s class list and its inline style. Since these things are attributes, we can use V-bind to handle them: just use an expression to compute a final string. But oh, manipulating string concatenation/operations is annoying and error-prone. For this reason,Vue provides a number of specialized enhancements when v-bind is used for class and style. Expression results can be objects and arrays as well as strings

Binding HTML Classes Bind the NAME of the HTML class

Object Syntax Object Syntax

We can pass an object to :class (short for v-bind:class) to dynamically toggle classes:

You can pass an object to :class to dynamically name the toggle class

<div :class="{ active: isActive }"></div>
Copy the code

The above syntax means the presence of the active class will be determined by the truthiness of the data property isActive

This syntax indicates that whether the active class name is displayed depends on whether the attribute value isActive is true or false.

You can have multiple classes toggled by having more fields in the object. In addition, the :class directive can also co-exist with the plain class attribute. So given the following template:

You can also manipulate multiple class name switches by making the object have more fields. In addition, the :class directive can coexist with the class attribute, giving the following template:

<div
  class="static"
  :class="{ active: isActive, 'text-danger': hasError }"
></div>
Copy the code

And the following data:

data() {
  return {
    isActive: true.hasError: false}}Copy the code

It will render:

<div class="static active"></div>
Copy the code

When isActive or hasError changes, the class list will be updated accordingly. For example, if hasError becomes true, the class list will become "static active text-danger".

When isActive and hasError values change, the class list is updated accordingly. For example, if hasError is set to true, the class list becomes “static Active text-danger”.

The bound object doesn’t have to be inline:

<div :class="classObject"></div>
Copy the code
data() {
  return {
    classObject: {
      active: true.'text-danger': false}}}Copy the code

This will render the same result. We can also bind to a computed property that returns an object. This is a common and powerful pattern

So this is going to have the same effect as the inline method. You can also bind data to a computed property and return an object-a common and efficient pattern.

<div :class="classObject"></div>
Copy the code
data() {
  return {
    isActive: true.error: null}},computed: {
  classObject() {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'}}}Copy the code

Array Syntax Array Syntax

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

We can pass an array to :class and apply a class list.

<div :class="[activeClass, errorClass]"></div>
Copy the code
data() {
  return {
    activeClass: 'active'.errorClass: 'text-danger'}}Copy the code

Which will render:

<div class="active text-danger"></div>
Copy the code

If you would like to also toggle a class in the list conditionally, you can do it with a ternary expression:

If you want to switch class names conditionally within a list, you can use a ternary expression:

<div :class="[isActive ? activeClass : '', errorClass]"></div>
Copy the code

This will always apply errorClass, but will only apply activeClass when isActive is truthy. As above, errorClass is constantly rendered, and activeClass is conditionally rendered based on isActive.

However, this can be a bit verbose if you have multiple conditional classes. That’s why it’s also possible to use the object syntax inside array syntax:

However, if you have more than one conditional statement, it’s a bit redundant. This is why it is possible to use object syntax in array syntax:

<div :class="[{ active: isActive }, errorClass]"></div>
Copy the code

With Components

This section assumes knowledge of Vue Components. Feel free to skip it and come back later This section assumes knowledge of Vue Components. If not, skip it. That’s fine.

When you use the class attribute on a custom component with a single root element, those classes will be added to this element. Existing classes on this element will not be overwritten.

For example, if you declare this component:

When you use class attributes on a custom Component that has only one root element, the class values are added to the root element. The class name already exists on it and will not be overwritten.

If you declare an element like this:

const app = Vue.createApp({})

app.component('my-component', {
  template: `

Hi!

`
}) Copy the code

Then add some classes when using it:

<div id="app">
  <my-component class="baz boo"></my-component>
</div>
Copy the code

Rendered HTML will be rendered rendered, rendered, and rendered accordingly.

<p class="foo bar baz boo">Hi</p>
Copy the code

Bindings: The same is true for class bindings:

<my-component :class="{ active: isActive }"></my-component>
Copy the code

Rendered HTML will be rendered When isActive is truthy, the rendered HTML will be rendered rendered rendered:

<p class="foo bar active">Hi</p>
Copy the code

If your component has multiple root elements, you would need to define which component will receive this class. You can do this using $attrs component property:

If the custom component has multiple root elements, you need to specify the element that receives the class name. This behavior can be accomplished with the $attrs component property:

<div id="app">
  <my-component class="baz"></my-component>
</div>
Copy the code
const app = Vue.createApp({})

app.component('my-component', {
  template: ` 

Hi!

This is a child component `
}) Copy the code

You can learn more about component attribute inheritance in Non-Prop Attributes section.

More on component attribute inheritance in the No Prop Properties section.

Binding Inline Styles Inline style Binding

Object Syntax Object Syntax

The object syntax for :style is pretty straightforward – it looks almost like CSS, except it’s a JavaScript object. You can use either camelCase or kebab-case (use quotes with kebab-case) for the CSS property names:

The object syntax for :style is straight white/simple/straightforward. CSS property names can be written either camelCase or kebab-case (enclosed in quotes), except that it is essentially a JS object.

<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
Copy the code
data() {
  return {
    activeColor: 'red'.fontSize: 30}}Copy the code

It is often a good idea to bind to a style object directly so that the template is cleaner:

It is a good idea to bind the template directly with a style object so that it looks clean.

<div :style="styleObject"></div>
Copy the code
data() {
  return {
    styleObject: {
      color: 'red'.fontSize: '13px'}}}Copy the code

Again, the object syntax is often used in conjunction with computed properties that return objects.

Again, object syntax is often used in conjunction with a computed property that returns an object.

Array Syntax Array Syntax

The array syntax for :style allows you to apply multiple style objects to the same element:

The array syntax for style allows multiple style objects to be applied to the same element:

<div :style="[baseStyles, overridingStyles]"></div>
Copy the code

Auto-prefixing Automatic prefix

When you use a CSS property that requires vendor prefixes in :style, for example transform, Vue will automatically detect and add appropriate prefixes to the applied styles.

When a CSS property (propety) in :style requires a third-party prefix, such as transform,Vue automatically detects it and adds the appropriate prefix.

Multiple Values more value

You can provide an array of multiple (prefixed) values to a style property, for example:

You can provide a multi-valued array (prefixed) for a sytle property, such as:

<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>
Copy the code

This will only render the last value in the array which the browser supports. In this example, it will render display: flex for browsers that support the unprefixed version of flexbox.

This renders the last value in the array (browser supported). In the example above, display: flex is rendered, provided that the browser supports flexbox without the prefix.