Binding Class Attributes Vue.js provides flexible ways to dynamically bind CSS classes using the v-bind directive, which can be abbreviated as a colon (:).
Object Literal Binding The class binding accepts an object literal where keys represent class names and values are boolean expressions determining whether the class should be applied.
<div id="dynamic-class">
<button :class="{ danger: isError, success: !isError }" @click="toggleStatus">
Status: {{ statusMessage }}
</button>
</div>
const app = new Vue({
el: '#dynamic-class',
data: {
isError: true,
messages: ['Error Occurred', 'Operation Successful'],
statusMessage: ''
},
computed: {
isSuccess() {
return !this.isError;
}
},
methods: {
toggleStatus() {
this.isError = !this.isError;
this.statusMessage = this.isError ? this.messages[0] : this.messages[1];
}
}
});
.danger {
background-color: #f44336;
color: white;
}
.success {
background-color: #4CAF50;
color: white;
}
Object Reference Binding Instead of inline objects, you can reference class objects defined in your Vue instance's data or compuetd properties.
const app = new Vue({
el: '#class-reference',
data: {
isActive: true,
statusText: 'Active'
},
computed: {
classObject() {
return {
active: this.isActive,
inactive: !this.isActive
};
}
},
methods: {
toggleClass() {
this.isActive = !this.isActive;
this.statusText = this.isActive ? 'Active' : 'Inactive';
}
}
});
Array Binding Classes can also be bound using an array of class names, which is useful when applying multipel classes conditionally.
<div :class="classList" @click="removeClass">
Click to remove classes
</div>
data: {
classList: ['large', 'bold']
},
methods: {
removeClass() {
if (this.classList.length > 0) {
this.classList.pop();
}
}
}
.large {
font-size: 1.5rem;
}
.bold {
font-weight: bold;
}
Binding Inline Styles Vue.js allows dynamic inline style binding using the v-bind:style directive, which accepts either object literals or arrays.
Object Literal Binding Style properties can be bound directly using JavaScript object syntax.
<div id="style-binding">
<div :style="styleObject" @click="increaseSize">
Click to increase size
</div>
</div>
const app = new Vue({
el: '#style-binding',
data: {
styleObject: {
color: 'blue',
fontSize: '14px'
}
},
methods: {
increaseSize() {
const currentSize = parseInt(this.styleObject.fontSize);
this.styleObject.fontSize = (currentSize + 2) + 'px';
}
}
});
Array Binding Multiple style objects can be applied by using an array syntax.
<div :style="[baseStyle, dynamicStyle]">
Styled content
</div>
data: {
baseStyle: {
fontFamily: 'Arial',
padding: '10px'
},
dynamicStyle: {
backgroundColor: 'lightgray'
}
}