Vue.js Style Binding
Vue.js Class
Class and style are attributes of HTML elements used to set the element's appearance. We can use v-bind
to set these attributes.
Vue.js enhances v-bind
specifically for handling class and style. The result types of expressions can be strings, objects, or arrays.
Class Attribute Binding
We can set an object for v-bind:class
to dynamically switch classes:
Example 1
In this example, setting isActive
to true
displays a green div block, and setting it to false
hides it:
<div v-bind:class="{ 'active': isActive }"></div>
The above example div class is:
<div class="active"></div>
We can also pass more properties in the object to dynamically switch multiple classes.
Example 2
The text-danger
class background color overrides the active
class background color:
<div class="static"
v-bind:class="{ 'active' : isActive, 'text-danger' : hasError }">
</div>
The above example div class is:
<div class="static active text-danger"></div>
We can also bind an object directly from the data:
Example 3
The text-danger
class background color overrides the active
class background color:
<div id="app">
<div v-bind:class="classObject"></div>
</div>
Example 3 renders the same result as Example 2.
Additionally, we can bind a computed property that returns an object. This is a common and powerful pattern:
Example 4
new Vue({
el: '#app',
data: {
isActive: true,
error: {
value: true,
type: 'fatal'
}
},
computed: {
classObject: function () {
return {
base: true,
active: this.isActive && !this.error.value,
'text-danger': this.error.value && this.error.type === 'fatal',
}
}
}
})
Array Syntax
We can pass an array to v-bind:class
as shown in the following example:
Example 5
<div v-bind:class="[activeClass, errorClass]"></div>
The above example div class is:
<div class="active text-danger"></div>
We can also use a ternary expression to toggle classes in the list:
Example 6
errorClass
is always present, and activeClass
is added when isActive
is true
:
<div v-bind:class="[errorClass ,isActive ? activeClass : '']"></div>
Vue.js Style (Inline Styles)
We can directly set styles with v-bind:style
:
Example 7
<div id="app">
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">tutorialpro.org</div>
</div>
The above example div style is:
<div style="color: green; font-size: 30px;">tutorialpro.org</div>
We can also bind to a style object for a clearer template:
Example 8
<div id="app">
<div v-bind:style="styleObject">tutorialpro.org</div>
</div>
v-bind:style
can use an array to apply multiple style objects to an element:
Example 9
<div id="app">
<div v-bind:style="[baseStyles, overridingStyles]">tutorialpro.org</div>
</div>
Note: When using v-bind:style with CSS properties that require specific prefixes, such as transform, Vue.js will automatically detect and add the appropriate prefixes.