Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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?

like image 357
a--m Avatar asked Dec 13 '25 17:12

a--m


1 Answers

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
    }
  }
}
like image 106
Tuqire Hussain Avatar answered Dec 16 '25 08:12

Tuqire Hussain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!