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?

1
  • 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 Commented Mar 16, 2018 at 10:22

1 Answer 1

5

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
    }
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Won't work with data. Also syntax is incorrect in computed example. But the approach is correct.
I'm trying your solution but it doesn't look like valid javascript. More info can be found here
I think I have something following your solution, here is the bin: 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 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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.