2

Given the props:

someBool = true;
someString = 'set-class'

This will add conditional-class as a class to the element when someBool is true:

v-bind:class="{'conditional-class': someBool}"

This will add set-class to the element as a class:

v-bind:class="someString"

How do I mix these two syntaxes?

Tried:

v-bind:class="{'conditional-class': someBool}" v-bind:class="someString"

Result: Vue does not support duplicate binds

Tried:

v-bind:class="[someString, {'conditional-class': someBool}]"

Result: only adds 'conditional-class'. Even when the order is reversed.

Tried:

v-bind:class="{'conditional-class': someBool, someString: true}"

Result: treats someString name as a string, class becomes conditional-class someString

2 Answers 2

4

You could use some ES2015 magic to create a computed property name:

:class="{'conditional-class': someBool, [someString]: true}"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names

Alternatively, one of the things you've already tried should work:

:class="[someString, {'conditional-class': someBool}]"

This is explicitly documented here:

https://v2.vuejs.org/v2/guide/class-and-style.html#Array-Syntax

I tried older versions of Vue but it seems to have been supported for a long time.

Both techniques are demonstrated here:

new Vue({
  el: '#app',

  data () {
    return {
      someBool: true,
      someString: 'class2'
    };
  }
});
.class1 {
  border: 1px solid red;
  padding: 5px;
}

.class1::before {
  content: 'I have class1';
}

.class2 {
  background: #eef;
  margin: 5px;
}

.class2::after {
  content: ' & class2';
}
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
  <div :class="{class1: someBool, [someString]: true}"></div>
  <div :class="[someString, {class1: someBool}]"></div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

Short answer

Use a computed:

v-bind:class="someComputed"

computed:{
    someComputed: function(){
        return (this.someBool ? "conditional-class" + " " : "") 
            + this.someString;
    }
}

But that's really the work-around if anyone else comes by scratching their head. OP is looking for a mix inside the binding, or a definitive "not this can't be done" from someone with the ability to be definitive.

Comments

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.