You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过三元表达式设置多个类名?Vue双弹窗场景下类绑定合并方案问询

Merging the Opacity Class Bindings

First, let’s break down what your current code does:

  • When popBox is closed (!popBox is true), the background gets opacity-100
  • When popBox is open, it switches to opacity-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'">

Can You Set Multiple Class Names with a Ternary Expression?

Absolutely! There are two common approaches to do this:

  1. 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'
    ]">
    
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 19:22:42