a--m
a--m

Reputation: 4782

Vuejs class-bind and class interpolation

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:

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?

Upvotes: 3

Views: 3306

Answers (1)

Tuqire Hussain
Tuqire Hussain

Reputation: 181

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
    }
  }
}

Upvotes: 5

Related Questions