Vue.js:如何在v-if场景下添加类?状态为Inactive时文字标红
Hey there! To make the text red when the status is "Inactive", you can use Vue's conditional class binding with either object syntax or a ternary expression. Here's how to do it step by step:
Step 1: Define the CSS Class
First, add this CSS to your stylesheet (either in a <style> tag or external CSS file):
.text-red { color: red; /* Optional: Add bold or other styles if needed */ font-weight: bold; }
Step 2: Update the Vue Class Binding
Modify your <td> element's v-bind:class directive to conditionally apply the text-red class when option.status is "Inactive".
Option 1: Object Syntax (Cleanest for Single Condition)
This is the most readable approach for a single conditional class:
<td v-for="option in selected_type" v-if="option.id == item.status" :class="{ 'text-red': option.status === 'Inactive' }"> @{{ option.status }} </td>
(Note: :class is the shorthand for v-bind:class—both work, but shorthand is widely used in Vue projects.)
Option 2: Ternary Expression (Useful for Multiple States)
If you might need to add other classes for different statuses later, a ternary expression gives you more flexibility:
<td v-for="option in selected_type" v-if="option.id == item.status" :class="option.status === 'Inactive' ? 'text-red' : ''"> @{{ option.status }} </td>
How It Works
- The object syntax checks if
option.status === 'Inactive'evaluates to true. If yes, it adds thetext-redclass; if not, it skips it. - The ternary expression returns
text-redwhen the condition is met, otherwise an empty string (no additional class applied).
Just ensure the string comparison matches exactly (it’s case-sensitive—so "Inactive" vs "inactive" will behave differently unless you normalize the status value first).
内容的提问来源于stack exchange,提问作者Jayjay

