Classes from Data
How an element looks often depends on a class: a sold-out cake is gray, the drink you picked is highlighted. With :class, the classes come from data. Usually you give it an object: each property is the name of a class, and its value says whether the element has the class:
<script setup>
const soldOut = true;
</script>
<template>
<p class="cake" :class="{ sold: soldOut }">Cheesecake</p>
</template>
<style scoped>
.sold {
color: #999;
text-decoration: line-through;
}
</style>When soldOut is true, the paragraph has the class sold, and when it's false, it doesn't. The plain class="cake" stays either way, and Vue puts both together: the page gets <p class="cake sold">. So write the classes that an element always has into class, and the ones that depend on data into :class.
The object can have more classes, each with its own condition, and a condition can be any expression:
<p :class="{ sold: soldOut, cheap: price < 4 }">Cheesecake</p>A class name with a hyphen has to be in quotes, as in any JavaScript object: { 'gluten-free': glutenFree }. Without them, the app doesn't run.
When the data changes while the app runs, the classes change with it. In the JavaScript course, you did that with classList.add() and remove(); here, you only change the data.
Instructions
- 1
When no slices are left, the cake should look sold out. Give the paragraph the class
soldwhenslicesis 0, with:class, and keep itsclass="cake". Click Sell a slice until none are left. - 2
The last slice should stand out: add the class
lastto the object, for whenslicesis 1. The paragraph turns yellow.