0 day streak
javascript / beginner
Snippet

Dynamic Class Binding

You can dynamically toggle CSS classes by passing an object to :class. If the value is true, the class is applied; if false, it is removed.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
<script setup>
import { ref } from 'vue';
const isError = ref(true);
</script>
<template>
<div :class="{ 'text-red': isError, 'bold': true }">
Status Message
</div>
</template>
vue
Breakdown
1
:class="{ 'text-red': isError }"
Applies 'text-red' only if the variable 'isError' is truthy.
2
'bold': true
A static class inside the object that is always applied.