Search code examples
javascriptvue.jsvuejs2vuetify.jscomputed-properties

VueJS/Vuetify different color chips in v-for, checking against an object with argument: color using dot notation


I'm trying to set the colors of a v-chip by using a method, passing an argument and trying to use dot notation to return a color string:

<v-chip :color="stateColor(bug.workflow_state)" text-color="white">{{ bug.workflow_state }}</v-chip>

The right value is being passed to the method. My argument: color object looks like this...

stateColors: {
  open: 'green',
  accepted: 'yellow',
  in_progress: 'orange'
}

...set in the data function. I want to be able to just return a la:

stateColor (bugState) {
  return this.stateColors.bugState
}

but the this.stateColors.bugState is undefined. The workflow_states being passed in will all match the keys, with no exceptions. This seems like it'd be more appropriate as a computed property, but I was also having issues with the dot notation returning the expected result. My attempt was like so:

stateColor: function () {
  return function (bugState) {
    return this.stateColors.bugState
  }
}

In both attempts, this.stateColors.open does return green, but this.stateColors.bugState where bugState is actually 'open' returns undefined. typeof(bugState) is definitely a string. Just looking for a clean way to achieve this without a slew of if checks, which I know would work.


Solution

  • You are just asking for the bugState property, which probably doesn't exist.

    Instead, ask for the key matching your bugState variable:

    return this.stateColors[bugState]