5

What is the proper way to bind class to a tag based on multiple conditions?

Given this tag, it seems that when trying to write multiple conditions one is being overwritten by another.

<q-tr :props="props" 
    :class=["(props.row.Name=='Row Name 1' || props.row.Name=='Row Name 2')?'text-bold':'bg-white text-black', (props.row.Name=='Row Name 3')?'text-green':'bg-white text-black']
>
</q-tr>

So in the above example text-bold class is overwritten by bg-white text-black since the second condition is overriding the first class binding.

Is there a way to structure conditions in if, else if, else style in vue class binding?

Alex T
  • 3,529
  • 12
  • 56
  • 105

1 Answers1

5

Bind that class attribute to a computed property called myClass :

<q-tr
    :class="myClass"
>
</q-tr>
computed:{
   myClass(){
     if(this.props.row.Name=='Row Name 1' ){
         return 'text-bold';
      }
      else if( this.props.row.Name=='Row Name 3'){
         return 'text-green';
      }
      else{
           return 'bg-white text-black'
      } 

   }

}
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • This sort of makes sense but actually does not work. I get error `TypeError: Cannot read property 'row' of undefined` – Alex T Aug 17 '20 at 07:01
  • Im not sure how should `props` be defines since its passed to the component there – Alex T Aug 17 '20 at 07:05