Vue / Basic: reactive components and input contracts / Lesson 7
Class bindings and visible state
Bind presentation to explicit state while retaining semantic controls and accessible status text.
On this page
Lesson goals
- Bind classes to reactive state.
- Derive presentation without duplicating state.
- Verify keyboard and nonvisual feedback.
- Derive class and style output from a single explicit state owner.
- Verify visual, semantic and interaction state together across transitions.
Separate state from presentation
A selected item has a state that can drive both behavior and appearance. Vue can bind a class object to that state instead of manually adding and removing DOM classes. Keep the state as the source of truth and make its meaning visible in text or semantics as well as color. A visual highlight alone cannot communicate a selection to every user.
Bind a class to a control
This single-file component toggles a boolean and binds it to a class and aria-pressed. The button remains a native keyboard-operable control, and its text changes with the same source value. The snippet requires a Vue single-file-component host and build tool; it is not a standalone browser document. The example uses font weight, but production styling needs a visible focus indicator too.
<script setup>
import { ref } from "vue";
const selected = ref(false);
</script>
<template>
<button :class="{ selected }" :aria-pressed="selected" @click="selected = !selected">
{{ selected ? "Selected" : "Select" }}
</button>
</template>
<style scoped>
.selected { font-weight: bold; }
</style>
Initially Select; after activation Selected.
One boolean controls the selected class, accessible pressed state, and visible button text.
Derive a class object
When several pieces of presentation depend on the same domain value, a computed property can express the mapping clearly. The example derives a warning class from a status without keeping a second writable warning flag. The caller or component must still decide how the status changes and how to explain an error; styling is not a substitute for an actionable message.
<script setup>
import { computed, ref } from "vue";
const level = ref("normal");
const noticeClass = computed(() => ({ warning: level.value === "warning" }));
</script>
<template><p :class="noticeClass">Status: {{ level }}</p></template>
<style scoped>.warning { font-weight: bold; }</style>
Initially Status: normal.
The computed object applies warning only when the status is warning.
Consider scope and input
Scoped styles apply through Vue’s compiled component styling rules, while inherited and child component styling have additional boundaries. Inspect the actual rendered element when a class appears ineffective. Avoid building arbitrary CSS or URLs from untrusted input; validate the permitted values at the relevant boundary. Separate layout choices from a status decision so changing a theme does not change application behavior.
Verify each state
Activate the button by keyboard and pointer, then confirm that text, aria-pressed and the class agree after each toggle. Test the status mapping for normal and warning values. Check focus visibility and contrast in the real theme, including high-contrast settings where supported. A class assertion alone does not demonstrate that a person can perceive or operate the control.
Start with state, then derive presentation
A class binding maps application state to CSS class names; the class is an output of the decision rather than a separate source of truth. A selected note may have a selected class, an aria-pressed value and a visible action label, all derived from one boolean. If those values are stored independently, one can change without the others and mislead users. Identify the owner of the state and the action that changes it before writing selectors.
Use a class object for conditional class names or an array for a combination of classes and expressions. Vue combines a static class with a dynamic binding on the same element. A computed object can make a repeated or more complex rule readable, but keep it a pure derivation. The examples use Vue 3.5.44 and synthetic data; they describe intended behavior and require a configured SFC compiler and host rather than claiming browser execution.
Read object and array bindings precisely
In an object binding, each key is a class name and its value determines whether that class is included. A false value omits the class while a true value includes it; the underlying CSS must still define what the class means. An array can combine a base class, a conditional expression and an object. Prefer a small explicit mapping over constructing opaque strings from untrusted input. A dynamic class does not by itself create a usable control, validate a value or authorize an action.
When a class rule depends on a status such as normal, warning or error, derive it from that status instead of maintaining a second warning flag. State transitions should occur at the appropriate owner, and the template should render the current decision. Test the complete set of expected classes after each transition, including removal of a previous class. The absence of a class definition may produce no visible difference even though the DOM binding is correct.
Expose state beyond color and decoration
Color and class names alone do not communicate a control’s meaning to every user. A toggle button needs an accessible name and an appropriate pressed state; bind aria-pressed to the same boolean that drives its visual class. Status text or an icon with an accessible alternative can distinguish warning and error states without relying only on color. Use native buttons for actions and preserve visible keyboard focus. A disabled attribute changes native interaction, while a dimmed class merely changes appearance.
Choose semantics for the actual interaction instead of applying aria-pressed to every highlighted element. Selection in a list, an expanded disclosure and a pressed toggle may require different roles or attributes. Check contrast, focus and announced state in a browser with appropriate assistive technology. A structural template test can check attributes and text, but it cannot by itself establish the quality of a visual design or the complete screen reader experience.
Understand style scope and value trust
A scoped SFC style limits selector matching using Vue’s compilation strategy; it does not isolate every inherited style or sanitize user content. Classes passed to a component can interact with its root element and component structure, so inspect the actual component contract rather than assuming all styles stay private. Avoid taking arbitrary user input as an executable template or treating a class name as a security decision. Untrusted URLs and HTML require their own validation and trust boundaries.
Inline style bindings can express a dynamic value, but validate the value against the intended design range and unit. A progress width derived from a number should clamp or reject out-of-range input according to the product rule, and it should have semantic text or an appropriate progress representation. Do not make important information available only through a background color or width. Test missing and unexpected status values as well as the normal path.
Verify the state transition as a whole
For a selected toggle, check the initial class, accessible name and pressed state, activate the button, then check all three again. For a status badge, verify normal, warning and error values and ensure stale classes are removed when status changes. Include an unexpected status so the fallback is visible and safe. A class assertion tests the binding; a browser check tests the actual styling, focus and interaction under the selected stylesheet.
Keep data, presentation and authorization tests separate. Hiding an action or applying a disabled-looking class cannot replace a server permission check. Record the viewport, component inputs and observed behavior when reporting a visual defect. A pure mapping test can establish which class is selected for a status, but it cannot establish that CSS was loaded or that the result is readable. Use the smallest test that addresses each claim, then cover the complete user interaction where needed.
20 worked examples
1. Conditional class object
Problem: Determine classes for one selected note.
- The static note class is always present.
- The object includes selected because its value is true.
<script setup>
const selected = true
</script>
<template><button class="note" :class="{ selected }">Note</button></template>
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The intended button has both note and selected classes.
Why this result follows: Vue merges the static class with truthy entries in the bound object.
2. False class condition
Problem: Predict the unselected class list.
- The static class remains regardless of the state.
- The false object entry omits the selected class.
<script setup>
const selected = false
</script>
<template><button class="note" :class="{ selected }">Note</button></template>
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The intended button has note but not selected.
Why this result follows: A false class-object value excludes its associated class.
3. One toggle source
Problem: Connect visual and semantic pressed state.
- Both bindings read the same selected ref.
- The click toggles that ref from false to true.
<script setup>
import { ref } from "vue"
const selected = ref(false)
</script>
<template><button type="button" :class="{ selected }" :aria-pressed="selected" @click="selected = !selected">Select note</button></template>
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The button starts unpressed without selected; one activation makes it pressed with selected.
Why this result follows: A single state owner keeps the class and pressed attribute aligned.
4. Status-derived class
Problem: Map warning status to a class.
- The status ref currently contains warning.
- The equality expression therefore evaluates to true.
const status = ref("warning")
const classes = computed(() => ({ warning: status.value === "warning" }))
// classes.value.warning is true
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The computed object enables warning for the supplied status.
Why this result follows: A pure derivation avoids a separately synchronized warning flag.
5. Array binding
Problem: Combine a stable base class and one conditional class.
- The first array entry always supplies note.
- The true condition selects active rather than idle.
<script setup>
const active = true
</script>
<template><p :class="['note', active ? 'active' : 'idle']">Draft</p></template>
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The intended paragraph has note and active classes.
Why this result follows: An array binding combines the selected class entries.
6. Remove a stale class
Problem: Trace a status transition from warning to normal.
- The binding reevaluates the equality against the current status.
- The expression becomes false when status is normal.
<script setup>
import { ref } from "vue"
const status = ref("warning")
</script>
<template><p :class="{ warning: status === 'warning' }">{{ status }}</p></template>
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: After status changes to normal, the paragraph text is normal and the warning class is absent.
Why this result follows: A derived binding removes a class when its condition no longer holds.
7. Multiple independent classes
Problem: Select classes for a busy invalid form.
- Both dynamic object values are true.
- The static editor class is merged with the dynamic entries.
<script setup>
const busy = true
const invalid = true
</script>
<template><form class="editor" :class="{ busy, invalid }"></form></template>
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The intended form has editor, busy and invalid classes.
Why this result follows: An object binding can represent independent presentation conditions.
8. Fallback status class
Problem: Choose a class for an unexpected status.
- paused is not a key in the defined mapping.
- The nullish fallback supplies a deliberate class instead of an undefined mapping.
function statusClass(status) {
return { normal: "badge-normal", warning: "badge-warning" }[status] ?? "badge-unknown"
}
// statusClass("paused") returns "badge-unknown"
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The unknown input maps to badge-unknown.
Why this result follows: An explicit fallback makes unexpected state visible to the presentation contract.
9. Computed class map
Problem: Derive mutually exclusive badge classes.
- Each entry compares the same source status to a distinct value.
- Only the error comparison matches the supplied value.
const status = ref("error")
const badgeClasses = computed(() => ({
normal: status.value === "normal",
warning: status.value === "warning",
error: status.value === "error"
}))
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: For error status, only the error entry is true.
Why this result follows: A single status source prevents independently stored flags from conflicting.
10. Class array with object
Problem: Combine base styling and a conditional warning.
- The array supplies badge as a stable class.
- The nested object includes warning because its value is true.
<script setup>
const warning = true
</script>
<template><p :class="['badge', { warning }]">Check title</p></template>
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The intended paragraph has badge and warning classes.
Why this result follows: Vue accepts object entries within a class array.
11. Native disabled versus dimmed
Problem: Compare behavior of a class and an attribute.
- A class name has no built-in disabled semantics.
- The disabled binding applies the native boolean attribute to B.
<template>
<button class="dimmed" type="button">A</button>
<button :disabled="true" type="button">B</button>
</template>
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: Button A is only styled by dimmed; button B has the native disabled state.
Why this result follows: Visual styling and native control behavior are separate browser mechanisms.
12. Status text alongside color
Problem: Expose a warning without relying on color alone.
- The word Warning and its explanation are visible content.
- The class may add styling but is not the only carrier of meaning.
<template><p class="warning"><strong>Warning:</strong> Title is missing</p></template>
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The warning is communicated by text as well as any CSS applied to warning.
Why this result follows: A textual status remains understandable when color is unavailable.
13. Focus style remains visible
Problem: Keep a keyboard focus indicator on an action.
- The selector targets the browser’s focus-visible state.
- The explicit outline and offset provide a visible styling rule under the stated condition.
button:focus-visible {
outline: 3px solid #003366;
outline-offset: 2px;
}
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: When the browser applies focus-visible, this rule provides an outline; actual contrast requires browser verification.
Why this result follows: A focus indicator communicates keyboard location independently of the selection class.
14. Clamp a progress width
Problem: Convert a bounded number into a style value.
- Math.max enforces the lower bound of zero.
- Math.min enforces the upper bound of one hundred.
function progressWidth(value) {
const safe = Math.min(100, Math.max(0, value))
return `${safe}%`
}
// progressWidth(130) returns "100%"
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The input 130 maps to 100% under this clamp policy.
Why this result follows: An explicit range policy prevents this numeric input from producing a width above 100%.
15. Style binding with units
Problem: Bind a computed width to a progress bar.
- The style object binds the width property to the supplied string.
- The text gives a readable value separate from visual width.
<script setup>
const width = "40%"
</script>
<template><div :style="{ width }">40 percent</div></template>
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The intended div has width 40% and displays the text 40 percent.
Why this result follows: A style binding transfers the value while visible text supplies an additional representation.
16. Component root class
Problem: Reason about a class passed to a single-root child.
- The child root already declares badge.
- The parent class falls through and is merged under the stated inheritance conditions.
<!-- Badge.vue: <template><span class="badge">Ready</span></template> -->
<!-- Parent: <Badge class="large" /> -->
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: For this single-root component with normal attribute inheritance, the root span receives badge and large.
Why this result follows: Class fallthrough combines parent and root classes for the usual single-root case.
17. Scoped style is not sanitization
Problem: Assess untrusted content in a styled component.
- The scoped attribute changes how the selector matches.
- Content interpretation is governed by the interpolation context, not the CSS rule.
<template><p class="note">{{ userText }}</p></template>
<style scoped>.note { color: navy; }</style>
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The scoped rule affects styling; normal interpolation displays userText as text and the style does not sanitize HTML.
Why this result follows: Presentation scope and content trust are separate boundaries.
18. Unknown class has no style
Problem: Diagnose a correct binding with no visible change.
- The DOM contains the expected class name.
- No matching CSS rule is present in the stated stylesheet.
DOM class: badge-warning
Loaded stylesheet: no .badge-warning rule
Observed: no color change
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The class binding may be correct, but the expected style is missing from the loaded stylesheet.
Why this result follows: A class name changes appearance only when applicable CSS supplies styling.
19. Selection is not authorization
Problem: Assess a visually hidden delete action.
- The class binding is client-side presentation.
- A caller can send a request independently of this button.
<template><button :class="{ hidden: !canDelete }" @click="remove">Delete</button></template>
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: The class may hide the button visually, but the server must still authorize deletion.
Why this result follows: CSS visibility cannot enforce a server-side permission boundary.
20. Test a complete transition
Problem: Choose assertions for a toggle from false to true.
- The class and pressed attribute derive from the same state change.
- The accessible name and actual interaction are separate observable parts of the control.
Initial: selected=false
Action: activate button
Expected: selected class present; aria-pressed="true"; label remains meaningful
This contextual example is not executed; a compatible Vue compiler and host are required where applicable.
Expected result: Check all three outputs after the activation and verify keyboard interaction in a browser.
Why this result follows: Testing the combined outputs detects visual and semantic state drifting apart.
Common errors and fixes
The visual class changes but assistive technology gets no state.
- Why it happens
- Selection is represented only by color or CSS.
- How to fix it
- Expose the appropriate semantic state and visible text.
- Prevent it next time
- Test keyboard and accessibility output together.
The status and highlight disagree.
- Why it happens
- Two writable flags represent the same decision.
- How to fix it
- Derive the class from the owned status.
- Prevent it next time
- Test every allowed status transition.
The class appears in the DOM but its style does not apply.
- Why it happens
- The selector or scoped styling boundary does not match the element.
- How to fix it
- Inspect the rendered element and applicable rules.
- Prevent it next time
- Test the component in its actual host and theme.
20 practice exercises
1. Why does the selection button use aria-pressed and text as well as a class?
Show hint
Separate the visual cue, accessible state and action name.
Show worked solution
The class supplies visual styling while aria-pressed exposes toggle state and the text identifies the action. They all derive from the same boolean so they can be verified together.
The class can style selection, aria-pressed communicates the toggle state and the button text names the action. Derive them from the same boolean where applicable and verify the full transition with keyboard interaction.
Check your solution
- The class and aria-pressed agree.
- The button retains a meaningful name.
2. A warning flag duplicates a status value. How can it be simplified?
Show hint
Identify the existing status as the authoritative source.
Show worked solution
Derive the class from the status using a computed value or template expression. Update the status at its owner and test normal and warning output.
A separate warning flag can drift from status. Derive the class from status with a computed value or template expression, update status at its owner and test both normal and warning output.
Check your solution
- The warning class follows status.
- A transition removes the previous class.
3. A reading-progress badge binds ["badge", complete ? "done" : "in-progress"]. If complete changes from false to true, predict both class lists.
Show hint
Evaluate the conditional array entry for each state.
Show worked solution
When complete is false, the badge has badge and in-progress. When complete becomes true, it has badge and done; the previous in-progress class is removed while the base class remains.
Check your solution
- Initially the classes are badge and in-progress.
- After completion the classes are badge and done, with in-progress absent.
4. A class object has busy true and invalid false. Which dynamic class appears?
Show hint
Inspect both object values.
Show worked solution
The busy class is included and invalid is omitted. Verify both conditions independently because a form can be busy and invalid at the same time under another state.
Check your solution
- Busy is present.
- Invalid is absent for this input.
5. A toggle is visually selected but aria-pressed remains false. Identify the design problem.
Show hint
Both outputs should share an owner.
Show worked solution
Derive the selected class and aria-pressed from the same boolean and update that owner on activation. Test initial and changed values together so the visual and semantic states cannot silently diverge.
Check your solution
- The class and attribute use one source.
- Both change after activation.
6. A warning flag duplicates status === warning. Simplify the state model.
Show hint
Derive rather than synchronize a copy.
Show worked solution
Keep status as the owner and derive the warning class with a computed value or template expression. Test normal and warning transitions and confirm the old class is removed.
Check your solution
- There is one status source.
- The warning class matches the status.
7. A badge receives an unknown status paused. Design a visible fallback.
Show hint
Do not leave the mapping undefined.
Show worked solution
Map known statuses to their classes and provide a deliberate unknown fallback for paused. Display meaningful text and investigate the unexpected input rather than silently presenting it as normal.
Check your solution
- Paused maps to a fallback.
- The text does not imply normal status.
8. A class array contains base and active ? selected : idle with active false. Predict output.
Show hint
Evaluate the conditional entry.
Show worked solution
The element receives base and idle, not selected. Test the true case too and ensure the relevant CSS rules exist in the loaded stylesheet.
Check your solution
- Base remains present.
- Idle replaces selected for false.
9. A button has a dimmed class but should be disabled during saving. Repair the behavior.
Show hint
A CSS class does not disable a native control.
Show worked solution
Bind the native disabled attribute to the saving state and provide a visible pending message. Test that the control is disabled while saving and enabled again after the operation finishes.
Check your solution
- The native disabled state follows saving.
- Pending feedback is visible.
10. A warning is shown only by a red background. Improve its communication.
Show hint
Do not rely only on color.
Show worked solution
Add meaningful warning text or an accessible alternative that describes the issue, then check contrast and screen reader output. Keep the class for visual styling as an additional cue.
Check your solution
- The warning has understandable text.
- Color is not its only signal.
11. A keyboard user cannot see which button has focus. Add a testable design requirement.
Show hint
Focus is separate from selected state.
Show worked solution
Provide a visible focus indicator such as a focus-visible outline and verify it with keyboard navigation in a browser. Check contrast and ensure other styles do not obscure the indicator.
Check your solution
- A focused button has a visible indicator.
- Keyboard navigation reaches the control.
12. A progress value 130 is converted to a width. Apply a zero-to-100 clamp.
Show hint
Enforce both bounds.
Show worked solution
Clamp the value to 100 and bind the resulting 100% width. Provide a textual or semantic progress value as well, and decide how invalid nonnumeric inputs should be handled.
Check your solution
- The resulting width is 100%.
- The value is communicated beyond width alone.
13. An inline width is built from untrusted input. What policy belongs before binding?
Show hint
Validate the intended value and unit.
Show worked solution
Parse and validate a permitted numeric range and produce a controlled unit such as percent. Reject or normalize unexpected input and test the boundary values before using the style binding.
Check your solution
- The value is within the allowed range.
- The unit comes from controlled code.
14. A single-root child has class badge and its parent supplies class large. Predict the usual result.
Show hint
Consider class fallthrough.
Show worked solution
With normal attribute inheritance, the root receives both badge and large. Verify the actual component structure and inheritance configuration because multi-root or customized behavior needs an explicit contract.
Check your solution
- The child root retains badge.
- The parent class is applied under the stated conditions.
15. A scoped style exists around user-supplied text. Does it sanitize the content?
Show hint
Selector scope differs from content trust.
Show worked solution
No. Scoped CSS controls selector matching and does not sanitize HTML. Use normal interpolation for text and a reviewed trust and sanitization strategy if rich content is required.
Check your solution
- Scoped styling is not treated as sanitization.
- The content uses an appropriate trust boundary.
16. The DOM has badge-warning but the appearance is unchanged. Name a likely next check.
Show hint
A class requires matching CSS.
Show worked solution
Inspect the loaded stylesheet and computed styles for a matching badge-warning rule, specificity or override. A correct class binding alone does not establish that the intended style is applied.
Check your solution
- The expected class is present.
- The matching CSS and overrides are inspected.
17. A delete button is hidden by a class for unauthorized users. Is the endpoint protected?
Show hint
Presentation is controlled by the client.
Show worked solution
No. The server must authenticate and authorize deletion independently because a caller can send a request without using the button. Test UI presentation and server permission as separate contracts.
Check your solution
- The server rejects unauthorized deletion.
- The hidden class is not treated as authorization.
18. A selected toggle changes from false to true. List three observable assertions.
Show hint
Check visual, semantic and naming output.
Show worked solution
After activation assert that the selected class is present, aria-pressed is true and the button retains a meaningful accessible name. Verify keyboard activation separately in a browser.
Check your solution
- The class and pressed state agree.
- The control remains named and keyboard operable.
19. A status changes from warning to normal. What class behavior should be verified?
Show hint
Look for stale output.
Show worked solution
Assert that the warning class is removed and the normal presentation appears according to the mapping. Verify the status text also changes so the visual cue and meaning remain consistent.
Check your solution
- The warning class is absent.
- The normal text and styling are present.
20. A pure function maps status to a class. What does its passing test not establish?
Show hint
The function does not load a stylesheet.
Show worked solution
It establishes the mapping for tested inputs but not that CSS exists, contrast is sufficient or the browser renders an accessible interaction. Check the component and browser boundaries separately.
Check your solution
- The mapping is tested for known and unknown input.
- CSS and accessibility receive separate checks.
Key takeaways
- Bind appearance to the owned state.
- Expose meaning through semantics and text, not color alone.
- Verify keyboard operation and actual styling.
- Classes represent state but do not replace semantic controls.
- One source can drive visual and accessible output consistently.
- A class test does not establish CSS readability or authorization.