Search code examples
classvue.jsconditional-binding

Vue Conditional Class Binding


I am trying to dynamically render class based off actionTypeCreate. This is a method that simply returns a boolean value based off the prop actionType that is passed. I am triggering this method on the mounted hook and confirmed it is returning properly.

Now I am trying to return the class value of 'col-md-4' if actionTypeCreate. If not actionTypeCreate I want to return the class 'col-md-6'.

This is what I have but it is not working:

:class="{toggleActionType : 'col-md-4' ? 'col-md-6'}"

I tried to reference this existing question, but I did not get it.


Solution

  • According to the Vue documentation itself you can do it in two ways. First, you can use Array Syntax and this is broadly used to apply a list of classes.

    Array Syntax

    :class="[toggleActionType ? 'col-md-4' : 'col-md-6']"
    

    Or you can do it as normal by Object Syntax but it does not accept ternary operations, so you have to do it this way:

    Object Syntax

    :class="{'col-md-4' : toggleActionType , 'col-md-6' : !toggleActionType}"