javascript / beginner
Snippet
Conditionally Displaying Badge Text with Switch and Primitive Types
In UI components, branching logic based on primitive string values is common for formatting human-readable badges. Utilizing a switch statement inside a computed property provides clear control flow, explicit fallbacks for unrecognized states, and optimal reactivity tracking.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { ref, computed } from 'vue';const orderStatus = ref('in_transit');const statusLabel = computed(() => {switch (orderStatus.value) {case 'pending':return 'Order Placed';case 'in_transit':return 'Out for Delivery';case 'delivered':return 'Completed';default:return 'Unknown Status';}});
vue
Breakdown
1
const orderStatus = ref('in_transit');
Initializes a reactive reference holding a primitive string representing the current state.
2
const statusLabel = computed(() => {
Defines a reactive computed getter that automatically recalculates whenever orderStatus changes.
3
switch (orderStatus.value) {
Evaluates the primitive string value of orderStatus against predefined cases.
4
case 'pending': return 'Order Placed';
Matches the 'pending' string identifier and returns the corresponding label.
5
case 'in_transit': return 'Out for Delivery';
Matches the active delivery state and returns the descriptive text.
6
default: return 'Unknown Status';
Provides a safe fallback string when the status does not match any expected case.