代码之家  ›  专栏  ›  技术社区  ›  Chris

如何在v-for循环期间有条件地更改表行样式?

  •  -1
  • Chris  · 技术社区  · 7 年前

    当global.globalGroupLevel为0时,我尝试在v-for循环中更改表行的背景色,如果不是0,则将其更改回原来的颜色。我知道我可以复制表中的行并使用v-if和v-else,但是那样看起来会很混乱。我曾考虑在tr元素上使用三元运算符来更改样式,但不确定这是否可行,如果可行,我也不知道如何实现。

    <tbody>
        <template v-for="global in orderItems">
            <tr>
                ... Bunch of code
            </tr>
        </template>
    </tbody>
    

    如前所述,我可以用这个。。。

    <tbody>
        <template v-for="global in orderItems">
            <tr v-if="global.globalGroupLevel == 0" style='background: #ccc'>
                ... Bunch of code
            </tr>
    
            <tr v-else="global.globalGroupLevel != 0" style='background: white'>
                ... Bunch of code
            </tr>
    
        </template>
    </tbody>
    

    但这是杂乱无章的,对于改变tr背景色来说是一件非常重要的事情。

    3 回复  |  直到 6 年前
        1
  •  1
  •   ssc-hrep3    7 年前

    您可以将解决方案与类一起使用,就像在另一个答案中提到的那样,或者使用 :style

    :style="{ background: global.globalGroupLevel == 0 ? '#ccc' : 'white' }"
    
        2
  •  1
  •   Boussadjra Brahim    7 年前

    whitebg graybg ,并按如下方式使用类绑定:

      <tr v-bind:class="{ global.globalGroupLevel == 0? 'graybg' : 'whitebg'}"></tr>
    

    CSS规则:

     .whitebg{
        background:white
        }
     .graybg{
        background:#ccc
     }
    
        3
  •  1
  •   Roland    7 年前

    作为最佳实践,我总是尽量避免内联样式,并将CSS保留在它的专用标记中。

    <tr :class="['gray-group', { 'white-group': global.globalGroupLevel }]"></tr>
    

    以及css:

    tr.gray-group {
      background: #ccc;
    }
    tr.white-group {
      background: white;
    }
    

    这里还有一个工作示例: js fiddle