TailwindCSS is actually a set of predefined CSS classes. If we want to change utility according to the state, we have to use Vue’s Class Binding.
Version
Vue 3.2
TailwindCSS 2.2
String
Class binding supports class
attribute is bound to String.
<script setup>
let fontColor = $ref ('text-red-600')
</script>
<template>
<div :class="fontColor">TailwindCSS</div>
</template>
class
attribute is bound to String which is state.
Object
Class binding supports class
attribute is bound to Object.
<template>
<div :class="{ 'text-red-600': true }">TailwindCSS</div>
</template>
Bind Object directly to class
attribute. Key is TailwindCSS’s utility, and value is boolean to enable or disable the utility.
Property Value
Class binding supports class
attribute is bound to Object’s property value only.
<script setup>
let isActive = $ref (true)
</script>
<template>
<div :class="{ 'text-red-600': isActive }">TailwindCSS</div>
</template>
class
attribute is bound to Object. Key is utility and value is isActive
state.
Whole Object
Class binding supports class
attribute is bound to the whole Object which is state.
<script setup>
let fontColor = $ref ({ 'text-red-600': true })
</script>
<template>
<div :class="fontColor">TailwindCSS</div>
</template>
class
attribute is bound to Object which is state.
Computed
Class binding supports class
attribute is bound to the whole Object which is Computed.
<script setup>
let fontColor = $computed (() => ({ 'text-red-600': true }))
</script>
<template>
<div :class="fontColor">TailwindCSS</div>
</template>
class
attribute is bound to Object which is Computed.
Array
Class binding supports class
attribute is bound to Array.
<script setup>
let fontSize = $ref ('text-3xl')
let fontColor = $ref ('text-red-600')
</script>
<template>
<div :class="[fontSize, fontColor]">TailwindCSS</div>
</template>
class
attribute is bound to Array with many utilities.
Object Array
Class binding supports class
attribute is bound to Object Array.
<script setup>
let fontColor = $ref ('text-red-600')
let isFontSizeActive = $ref (false)
</script>
<template>
<div :class="[{ fontSize: isFontSizeActive }, fontColor ]">TailwindCSS</div>
</template>
class
attribute is bound to Array with Object and Primitive mixed- Some utilities are Object with enable/disable by State
- Some utilities are just elements of Array
Computed
Class binding supports class
attribute is bound to Array which is Computed.
<script setup>
let fontStyle = $computed (() => ['text-3xl', 'text-red-600'])
</script>
<template>
<div :class="fontStyle">TailwindCSS</div>
</template>
class
attribute is bound to Array which is Computed.
Conclusion
- Class binding supports Object, Array and Computed.
- If we want to apply many utilities, besides using Array, we can also use Object Array