0

I'm trying to figure out how to bind classes to a table row conditionally based on a vue model.

IN my blade I have:

.low-priority{
    background-color: purple;
}
.high-priority{
    background-color: orange;
}
.important-priority{
    background-color: yellow;
}
.critical-priority{
    background-color: red;
}

and in my vue template I return a dateEvents object which has a value called priority which can be "High", "Low", "Important" or "Critical".

I want to set the class of this table row by those priorities:

<tr v-bind:class="dateEvent">

I've seen the docs for binding a class if a return is true or false, but how do I do this appropriately with conditionals, i.e. if dateEvent.priority === 'Low' then class is .low-priority'

Andrew Vasylchuk
  • 4,671
  • 2
  • 12
  • 30
Geoff_S
  • 4,917
  • 7
  • 43
  • 133

1 Answers1

1

Not sure you need a conditional in this case:

<tr :class="`${dateEvent.priority.toLowerCase()}-priority`">

Or if you don't like backticks:

<tr :class="dateEvent.priority.toLowerCase() + '-priority'">

A more general solution would be to use a computed property. In the circumstances that would be a bit repetitive though.

<tr :class="rowClass">
computed: {
  rowClass () {
    const priority = this.dateEvent.priority

    return {
      'low-priority': priority === 'Low',
      'high-priority': priority === 'High',
      'important-priority': priority === 'Important',
      'critical-priority': priority === 'Critical'
    }
  }
}

If dateEvents isn't available via this because it's a loop parameter (i.e. from v-for) then you'd make rowClass a method instead and pass in dateEvents from the template.

Other variations on that theme are available: https://v2.vuejs.org/v2/guide/class-and-style.html

tony19
  • 125,647
  • 18
  • 229
  • 307
skirtle
  • 27,868
  • 4
  • 42
  • 57