Vue Style Binding
Data-driven styling is a very powerful feature of Vue. We can use the v-bind directive (usually abbreviated as :) to dynamically manipulate an element's class and inline style.
Binding HTML Class
We can pass an object to :class to dynamically toggle classes.
Object Syntax
<script setup>
import { ref, reactive } from 'vue'
const isActive = ref(true)
const hasError = ref(false)
const classObject = reactive({
active: true,
'text-danger': false
})
</script>
<template>
<!-- When isActive is true, the 'active' class will be applied -->
<div :class="{ active: isActive, 'text-danger': hasError }"></div>
<!-- Can also bind to a data object -->
<div :class="classObject"></div>
<!-- Can also coexist with a normal class attribute -->
<div class="static" :class="{ active: isActive }"></div>
</template>Array Syntax
We can also pass an array to :class to apply a list of classes:
<script setup>
import { ref } from 'vue'
const activeClass = ref('active')
const errorClass = ref('text-danger')
</script>
<template>
<div :class="[activeClass, errorClass]"></div>
<!-- Can also use ternary expressions in the array -->
<div :class="[isActive ? activeClass : '', errorClass]"></div>
<!-- Nested objects in the array -->
<div :class="[{ active: isActive }, errorClass]"></div>
</template>Binding Inline Style
We can use :style to bind inline CSS styles.
Object Syntax
The object syntax for :style is very intuitive—it looks almost like CSS, but it's actually a JavaScript object. CSS property names can be written in camelCase or kebab-case.
<script setup>
import { ref } from 'vue'
const activeColor = ref('red')
const fontSize = ref(30)
</script>
<template>
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
<!-- Can also directly bind to a style object -->
<div :style="styleObject"></div>
</template>
<script>
export default {
data() {
return {
styleObject: {
color: 'red',
fontSize: '13px'
}
}
}
}
</script>Array Syntax
We can also bind an array containing multiple style objects to :style. These objects will be merged and applied to the element.
<template>
<div :style="[baseStyles, overridingStyles]"></div>
</template>Automatic Prefixing
When you use a CSS property in :style that requires a browser engine prefix, such as transform, Vue will automatically detect and add the corresponding prefix. Vue checks for supported properties at runtime, and if the current browser doesn't support a certain property, Vue will test various prefixed variants. For example, flex will automatically attempt to add -webkit-flex and -ms-flex prefixes.