3

In the view I need to generate the following classes:

<div class="comp comp--lock comp--red">Foo</div>

The lock and red are based on state, where the following values for color are possible:

  • comp--red, comp--yellow, comp--blue, and many other possible colors

Until now I was using a computed method to concatenate the class name based on data:

getCompClassName(){
  return `comp ${this.isLock ? 'comp--lock' : ''} comp--${this.color}`
}

Looking at Vuejs documentation I see there is v-bind:class that should resolve this in a better way, the problem I have is how to solve the color interpolation, since I would need to declare all possible colors.

data: {
  classObject: {
    'comp--lock': this.isLock,
    'comp--red': this.color === 'red',
    'comp--blue': this.color === 'blue',
    'comp--yellow': this.color === 'yellow'
  }
}

Is there any way to solve this using v-bind:class that scales better without having to list all possibilities or should I use the computed method to interpolate the class name?

a--m
  • 4,716
  • 1
  • 39
  • 59
  • Computed property will be good plus you get the additional benefit of caching as computed properties are not re calculated on every re-render unless its dependencies change – Vamsi Krishna Mar 16 '18 at 10:22

1 Answers1

4

Could you not just use a computed?

computed: {
  classObject() {
    return {
      'comp--lock': this.isLock,
      [`comp--${this.color}`]: true
    }
  }
}

JSfiddle: https://jsfiddle.net/5sknyauz/5/

EDIT: you could actually do the same thing in data:

data() {
  return {
    classObject: {
      'comp--lock': this.isLock,
      [`comp--${this.color}`]: true
    }
  }
}
Tuqire Hussain
  • 171
  • 1
  • 11
  • Won't work with data. Also syntax is incorrect in computed example. But the approach is correct. – dfsq Mar 16 '18 at 10:30
  • I'm trying your solution but it doesn't look like valid javascript. More info can be [found here](https://stackoverflow.com/a/35902149/220272) – a--m Mar 16 '18 at 10:49
  • I think I have something following your solution, here is the bin: http://jsbin.com/qajokim/3/edit?css,js,output . To make it work I've changed the `key` value like `[\`comp--${this.color}\`]`. Not sure how valid is this, but it works – a--m Mar 16 '18 at 11:04
  • 1
    @a--m yes apologies, forgot the square brackets. Updated the answer and added a JSFiddle link. I'm pretty sure it is perfectly valid (at least I do it all the time). – Tuqire Hussain Mar 16 '18 at 11:18