In Vue, we can dynamically bind CSS classes and styles to HTML elements using various approaches.
This allows us to apply styles conditionally based on data properties, making your application's UI more flexible and interactive.
We can bind CSS classes conditionally using an object syntax with the "v-bind:class" directive (:class shorthand).
The keys of the object represent class names, and the values represent conditions to apply those classes.
<div :class="{ 'active': isActive, 'error': hasError }"> Dynamic Classes </div>
Note: the "active class" will be applied if "isActive" is true, and the "error" class will be applied if "hasError" is true.
<div :class="[isActive ? 'active' : '', hasError ? 'error' : '']"> Dynamic Classes </div>
We can also use an array syntax to bind multiple CSS classes conditionally.
Note: the "active class" will be applied if "isActive" is true, and the "error class" will be applied if "hasError" is true.
<template> <div :class="computedClasses"> Dynamic Classes </div> </template> <script> export default { name: "App", data() { return { isActive: true, hasError: true, } }, computed: { computedClasses() { return { 'active': this.isActive, 'error': this.hasError }; } } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } .active { color: green } .error { color: red } </style>
We can define a computed property to dynamically compute the CSS classes based on component data.
<div :style="{ color: textColor, fontSize: fontSize + 'px' }"> Dynamic Styles </div>
We can bind inline styles dynamically using an object syntax with the "v-bind:style" directive (:style shorthand).
<template> <div :style="computedStyles"> Dynamic Classes </div> </template> <script> export default { name: "App", data() { return { textColor: "red", fontSize: 30, } }, computed: { computedStyles() { return { color: this.textColor, fontSize: this.fontSize + 'px' }; } } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } .active { color: green } .error { color: red } </style>
The keys of the object represent CSS properties, and the values represent their corresponding values.
Note: the "color" style will be set to the value of "textColor", and the "fontSize" style will be set to the value of "fontSize" plus 'px'.
Similar to CSS classes, we can define a computed property to dynamically compute the inline styles based on component data.