Vue3 Fundamentals · Rendering & Templates

Class bindings

Class binding

Class bindings

A button should look active in one state and inactive in another. You could write two buttons and show one, but the markup is identical apart from the class — you want the class itself to follow your data.

Vue binds class like any other attribute, but it accepts more than a string. The most useful form is an object whose keys are class names and whose values are conditions:

<button :class="{ active: isActive }">Save</button>

When isActive is true, Vue adds the active class; when it is false, Vue removes it. You can list several classes in the object, and each one is toggled by its own condition.

Because :class merges with any static class you also write, you can keep the classes that never change separate from the ones that toggle.

Your job is to toggle a class from a boolean instead of hard-coding it.

Challenge

The button is always styled the same, so it never shows its active state. Export an App component from App.vue that binds the button's class to an object toggling active on isActive, so the button carries the active class.

The Test mounts your component and reads the button's classes. The starter hard-codes a class, so the Test fails — use :class with an object.

App.vue
<script setup>
const isActive = true;
</script>

<template>
  <button class="button">Save</button>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.