如何通过三元表达式设置多个类名?Vue双弹窗场景下类绑定合并方案问询
First, let’s break down what your current code does:
- When
popBoxis closed (!popBoxis true), the background getsopacity-100 - When
popBoxis open, it switches toopacity-60 - The exact same logic applies to
popDeleteBox
To merge these two conditions, you just need to check if either popup is open. If either popBox or popDeleteBox is truthy, apply opacity-60; otherwise, use opacity-100. Here’s the simplified combined code:
<div :class="[(popBox || popDeleteBox) ? 'opacity-60' : 'opacity-100']">
You can even omit the array wrapper since it’s a single conditional class (though the array syntax works perfectly fine too):
<div :class="(popBox || popDeleteBox) ? 'opacity-60' : 'opacity-100'">
Absolutely! There are two common approaches to do this:
Space-separated classes in the ternary result:
If you want to apply multiple classes based on the same condition, just list them separated by spaces:<div :class="[ (popBox || popDeleteBox) ? 'opacity-60 bg-gray-900' : 'opacity-100 bg-white' ]">Multiple ternary checks in the class array:
For independent conditional classes, you can include separate ternary expressions in the array. This keeps each class toggle logic distinct:<div :class="[ (popBox || popDeleteBox) ? 'opacity-60' : 'opacity-100', isDarkTheme ? 'text-white' : 'text-gray-800', isLoading ? 'pointer-events-none' : 'cursor-pointer' ]">
This approach keeps your class bindings clean and readable, even when handling multiple conditional styles.
内容的提问来源于stack exchange,提问作者Dario Marjanovic

