Vue.js Style Binding
Vue.js class
class and style are attributes of HTML elements used to set element styles; we can use v-bind to set style attributes.
When handling class and style, Vue.js's v-bind has been specially enhanced. Besides strings, the expression result type can also be an object or an array.
Class Attribute Binding
We can pass an object to v-bind:class to dynamically toggle classes:
Example 1
In the example, setting isActive to true shows a green div block; if set to false, it does not show:
<div v-bind:class=">{ 'active': isActive }
"
div
Try it »
The div class in the above example is:
We can also pass more properties in the object to dynamically toggle 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
Try it »
The div class in the above example is:
We can also directly bind an object 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>Try it »
Example 3 and Example 2 produce the same rendering result.
In addition, we can also bind a computed property that returns an object here. 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
'
,
}
}
}
}
)
Try it »
Array Syntax
We can pass an array to v-bind:class ; the example is as follows:
Example 5
<div v-bind:class=">[activeClass, errorClass]
"
div
Try it »
The div class in the above example is:
We can also use a ternary expression to toggle a class in the list:
Example 6
errorClass is always present; when isActive is true, the activeClass is added:
<div v-bind:class=">[errorClass ,isActive ? activeClass : '']
"
div
Try it »
Vue.js style (inline styles)
We can in v-bind:style set styles directly:
Example 7
<div id="app">
<div v-bind:style=">{ color: activeColor, fontSize: fontSize + 'px' }
"
Runoob Tutorial
div
div
Try it »
The div style in the above example is:
Runoob Tutorial
You can also bind directly to a style object to make the template clearer:
Example 8
<div id="app">
<div v-bind:style="styleObject">Runoob Tutorial
div
div
Try it »
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]
"
Runoob Tutorial
div
div
Try it »
Note: when v-bind:style uses CSS properties that require a specific prefix, such as transform, Vue.js automatically detects and adds the corresponding prefix.